- Home /
How to effect all objects in an array
Hi. I have an enemy fully rigged with rigid bodies on each bone. I want it so that when his health is <=0 (which I already programmed), his rigid body in each bone will change from isKinematic true to isKinematic false (so that he becomes a ragdoll).
{
private Animator enemyanimator;
public GameObject enemy;
public Component[] bonerigidbodies;
public float health = 1;
public void takeDamage(float amount)
{
health -= amount;
if (health <= 0f)
{
die();
}
}
void die()
{
enemy.GetComponent<Animator>().enabled = false;
foreach (Rigidbody rigidbody in bonerigidbodies)
{
rigidbody.isKinematic = false;
}
}
private void Start()
{
bonerigidbodies = GetComponents<Rigidbody>();
}
}
Right now it only seems to make "isKinematic" false to the body part that you shoot, but not all the other body parts. For bonerigidbodies, I dragged the gameobjects of every bone into the array from the unity editor.
If this script is for the root object, then you have to use GetComponentsInChildren to get all the RigidBody components in the hierarchy. GetComponents only searches for components in the GameObject this script is attached to. You filled the array in the editor, but you reassign the array variable in Start, so it gets overwritten. So, you could also remove the line in Start() in s$$anonymous$$d of using GetComponentsInChildren.
Answer by Marten01 · May 19, 2018 at 10:37 AM
Remove the bonerigidbodies = GetComponents<Rigidbody>();
in the Start() method.
Reply with comments, not by posting a new answer.
Why didn't you include the error message if there was one?
Answer by jonnydredd · May 20, 2018 at 07:49 AM
try Rigidbody[] bonerigidbodies = gameObject.transform.root.GetComponentsInChildren<Rigidbody>();
Your answer
