I'm trying to remove a rigidbody from a transform in my script and I get this error: "MissingFieldException: Field 'UnityEngine.Rigidbody.enabled' not found." Here's my code:
transform.GetComponent(Rigidbody).enabled = false;
is there a way to remove it, or disable it? this same code works when I replace "Rigidbody" with the name of a script that's attached to the transform.
Ps. I also tried:
transform.GetComponent("Rigidbody").enabled = false;
and
transform.GetComponent(typeof(Rigidbody)).enabled = false;
but I get the same error.
8 Answers
8
there we go, I found this in the scripting manual, under addComponent():
"Note that there is no RemoveComponent(), to remove a component, use Object.Destroy."
so the code is simply this:
// Removes the rigidbody from the game object
Destroy (rigidbody);
that was easy.
You're trying to operate on a vanilla "UnityEngine.Object" reference. Use the generic version to get a specialized reference:
transform.GetComponent<Rigidbody>().enabled = false;
or, more simply, if rigidbody had an enabled:
rigidbody.enabled = false;
you don't need to use transform to get at GetComponent, and rigidbody is the property to get at the rigidbody more easily
but anyway - rigidbody doesn't have an enabled - you need to either remove the rigidbody, set the gameobject inactive or set isKinematic = true
In C#
UnityEngine.Object.Destroy(gameobjectinstance.GetComponent<RigidBody>());
If you want to change the prefab you have to load it, save it three times and reload the asset database at the start and the end of the script. I hate black magic! Hope unity version 3 fixes some of these issues.
I hope this is what you need - You can remove the physics from the game object if you enable the rigidbody’s isKinematic parameter in the script: (Javascript)
rigidbody.isKinematic = false; // enable physics
rigidbody.isKinematic = true; // disable physics
Destroy (GetComponent());
do Destroy(transform.rigidbody);
If you can’t destroy rigidbody than script depends on it… check at the bottom of script and comment that line.
In Unity 4.0+ rigidbody.active is deprecated and may no longer be available but you can do this:
rigidbody.detectionCollisions = false;
Destroy(rigidbody);
– anon85704231