- Home /
How to Remove Multiple Components of Same Type from Game Object?
I have a gameObject with multiple FixedJoints attached to it. I can't figure out how to remove these components from the gameObject. I read that you are supposed to use Destroy(Object o), but I wasn't sure how to do that with multiple components.
I'm upvoting you for enlightening me to the fact that one game object can have multiple components of the same type, for some reason I thought you couldn't. Thanks!
Answer by parahunter · Feb 07, 2011 at 09:38 PM
Okay I got this piece of code to work:
HingeJoint[] joints = GetComponents<HingeJoint>();
foreach(HingeJoint joint in joints)
Destroy(joint);
What you do wrong is that you cast the HingeJoints to Component when you store them but don't delete them as HingeJoint when you use destroy on them. I was not sure of this myself but I got this piece of code to work that sorta resembles your code (except I use a generic version of GetComponents which in my experience has proven to be the most predictable and stable way to use GetComponent and GetComponents):
Component[] joints = GetComponents<HingeJoint>() as Component[];
foreach(Component joint in joints)
Destroy(joint as HingeJoint);
This code also works :-)
Answer by parahunter · Feb 06, 2011 at 07:03 PM
You have to use the GetComponents method, loop trough them and then call Destroy() on all of the components that are returned from GetComponents. It's page on the documentation explains how you use it and loop trough the found components afterwards.
Thanks, but this doesn't seem to work. I printed out the length of the array returned by GetComponents before and after I Destroyed each component, and the all of the components were still there.
Then you probably called Destroy the wrong way. try to post your code here and I'll take a look at it
Component[] joints = myGameObject.GetComponents(typeof(FixedJoint)) as Component[]; for(FixedJoint j in joints) Destroy(j);