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);
}
}