- Home /
Can't remove Rigidbody from transform in script?
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.
Answer by Jordan Miller · May 05, 2010 at 06:58 PM
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.
Answer by Max Kaufmann · May 05, 2010 at 06:42 PM
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;
ok, i tried that but it didn't work either. (I'm doing this in JavaScript by the way) I still get that error along with the following: "expecting an identifier, found ')'." and "expecting ), found '.'" and "';' expected. Insert a semicolon at the end." is your code for C# or something?
Answer by Mike 3 · May 05, 2010 at 06:50 PM
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
ok, I tried that too. and I get this error, "'enabled' is not a member of 'UnityEngine.Rigidbody'." and I also get the error I was originally getting.
thanks mike, I can't believe how simple that turned out to be.
Answer by cob · May 11, 2010 at 06:18 PM
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.
Answer by nick_taras · Nov 29, 2012 at 11:33 AM
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