How to make sure GetComponentsInChildren<>() select the right components?

I am adding ragdolls to my game and I want to make sure that, while the enemy is not dead, the ragdoll’s rigidbodies don’t interfere, and instead have a single rigidbody inside the enemy’s parent object that is activated. When the enemy dies, the main rigidbody is deactivated and the ragdoll is activated. The ragdoll is made up of multiple smaller rigidbodies inside child objects, which are referenced in an array.

I always had trouble making sure GetComponent<>() and it’s variants don’t select the wrong components especially when working with child objects. I was able to find a workaround but I feel like there must be some way of doing this in a simpler way, maybe one that uses the very rarely used parenthesis the GetComponent<>() method has.

Here is my workaround (all of it sits in void Awake ()):

        MainRigidbody = GetComponent<Rigidbody>();
        MainCollider = GetComponent<Collider>();
        RagdollRigidbodies = GetComponentsInChildren<Rigidbody>();
        RagdollColliders = GetComponentsInChildren<Collider>();

        for (int i = 0; i < RagdollColliders.Length; i++)
        {
            if (RagdollColliders [i] == MainCollider)
            {
                RagdollColliders [i] = null;
            }

            if (RagdollColliders != null)
            {
                RagdollColliders [i].enabled = true;
            }
        }

        for (int i = 0; i < RagdollRigidbodies.Length; i++)
        {
            if (RagdollRigidbodies [i] == MainRigidbody)
            {
                RagdollRigidbodies [i] = null;
            }

            if (RagdollRigidbodies[i] != null)
            {
                RagdollRigidbodies [i].isKinematic = true;
                RagdollRigidbodies [i].useGravity = false;
                RagdollRigidbodies [i].mass = RagdollMass;
                RagdollRigidbodies [i].velocity = new Vector3(0f, 0f, 0f);
                RagdollRigidbodies [i].angularVelocity = new Vector3(0f, 0f, 0f);
            }
        }

You do not have any control over which components are going to be picked up by GetComponentsInChildren().

You’ll have to filter results by yourself. Add an extra component, or set object tag, or put the child bodies onto different layer, or just specify the root ragdoll object as a property that you have to set manually.

“Extra component” means making an empty component like

public class RagdollPart: MonoBehavior{   
}

Adding it to every child ragdoll part, and checking if it is present when you’re enabling child ragdolls.

1 Like