C#Deactivating child rigidbodies of an object

I want to market kinematic=false on all child transforms of an object. How would I do that?

It has a lot of transforms to go through, so I’m a bit confused with how I would accomplish this.

If you want to set it on all the childrens rigidbodies (including the childrens children), you can simply use GetComponentsInChildren(); which will return an array of rigidbodies that include everything from the script-holding objects rigidbody ( if there is one) all the way down the hierarchy.

Afterwards you can iterate through the array and deactivate isKinematic of every rigidbody in that list.
In order to not deactivate the rigidbody’s isKinematic attribute of the object that holds the script, you first have to check if that object has got a rigidbody component and if so, start the iteration with index 1, otherwise with 0.
That check can be done in several different ways.

I hope that helps.

Are you sure that the immediate object’s rigidbody would always be at index 0? I’ve never looked into it, but I’ve always assumed that the order was unreliable (much like the transform order in the hierarchy and script execution order when not explicitly assigned).

Not 100% sure, i only ran a few tests and it was always at the first position, so i just assumed that the search starts with the object which holds the script.
But that’s a good point, it’s nothing to rely on.

I’d say in the iteration loop, you could always get the rigidbody’s gameObject and compare it (i.e. its reference) to the reference of this.gameObject. If it’s the same, it’s the same object which is being referenced. Well, also not a method to rely on since ‘==’ could be overloaded and do something different, but as far as i know it’s not for GOs.

Yep, that’s what I generally do. Just didn’t know if you had information I didn’t.

1 Like

So all I need is GetComponentsInChildren(); and to specify what components I want to deactivate? Also, I am new to unity, where is this list?

GetComponentsInChildren
The array (to be exact, a reference to it) will be returned by the method, sorry for calling it a list. That might have caused confusion.

So you declare an array variable with the type of component you want to find and use the method (i would recommend the generic version in C#, not sure about JS/US) i mentioned in order to receive the reference to the array which will be created within that method.
After that, you can use a loop (for-loop or foreach-loop) in order to access the single elements in that array.

If you need further help or a code example, let us know.

Could I get a code example? I’m still having a hard time understanding.

Example:

Rigidbody[] allRBs = GetComponentsInChildren<Rigidbody>();
for (int r=0;r<allRBs.Length;r++) {
allRBs[r].isKinematic = true;
}
1 Like