A component that tracks an attached GameObject and cleans up constraint-related components when the attachment is removed. If the Attachment is destroyed, it either destroys this whole GameObject or removes specific joint/rope/line components depending on DestroyOnDetach.
internal class ConstraintCleanup : Component
{
[Property]
public GameObject Attachment { get; set; }
[Property]
public bool DestroyOnDetach { get; set; } = true;
protected override void OnDestroy()
{
if ( Attachment.IsValid() )
{
Attachment.Destroy();
}
base.OnDestroy();
}
protected override void OnUpdate()
{
if ( Attachment.IsValid() ) return;
if ( DestroyOnDetach )
{
DestroyGameObject();
return;
}
GetComponent<SpringJoint>()?.Destroy();
GetComponent<VerletRope>()?.Destroy();
GetComponent<LineRenderer>()?.Destroy();
Destroy();
}
}