- Home /
Deleting a rigidbody
I need to delete a rigidbody for my group to function. I have dragable parts that join into a group on collision. But the parts still move separately unless I manually delete their rigidbodies. But how do I do this through a c# script? I have tried this:
public class ObjectAttach : MonoBehaviour {
public Transform Group1;
void Start()
{
Group1 = GameObject.FindWithTag("Group").transform;
}
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag=="Part")
{
collision.transform.parent = Group1;
GameObject.FindGameObjectsWithTag("Part").Destroy(Rigidbody);
}
}
}
But that gives me this error:
Assets/Resources/ObjectAttach.cs(23,67): error CS1061: Type UnityEngine.GameObject[]' does not contain a definition for
Destroy' and no extension method Destroy' of type
UnityEngine.GameObject[]' could be found (are you missing a using directive or an assembly reference?)
What do I do?
Would making them $$anonymous$$inematic have the same effect you are after?
As an alternate to deleting the rigidbody, you could connect the rigidbodies together using a FixedJoint.
@robertbu - Good call, except that in this case that would require maintaining a chain of FixedJoints linking all objects in the group as he is grouping them by a single Transform that for all we know doesn't belong to a single object with a Rigidbody they could all join to.
....or parent them all to an another object, so you can just move that one?
Answer by Roland1234 · Dec 08, 2013 at 09:05 PM
You are trying to call .Destroy off of what FindGameObjectsWithTag returns, which is an array of GameObjects, not a singular GameObject. Based on the description of your problem, if you want to remove the Rigidbody component of the thing that you've collided with you would do the following:
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag=="Part")
{
collision.transform.parent = Group1;
if(collision.rigidbody != null)
{
Destroy(collision.rigidbody);
}
}
}
Although I world agree with meat5000's comment and suggest that making the rigidbody kinematic may be more appropriate.
Thanks for your answer. I can not make the rigidbody kinematic, as I have a script that makes them kinematic whenever they are not being dragged, so that they don't fly off if hit.
You would know best of course about the specific requirements for your project, but as far as the original question goes (how to delete a Rigidbody component in a script) please accept my answer as it does answer your original question. Gotta rack them points up, you know? ;)