How do I add a rigidbody in script?


Is it possible to add a rigidbody to a MonoBehaviour object in code? If so, how would I do this?

I'm hoping to have no rigidbody on the object and then add one to it on a button press.

Cheers :)

You need a reference to your gameObject, and then you use AddComponent:

C# Code:

GameObject myGameObject = new GameObject("Test Object"); // Make a new GO.
Rigidbody gameObjectsRigidBody = myGameObject.AddComponent<Rigidbody>(); // Add the rigidbody.
gameObjectsRigidBody.mass = 5; // Set the GO's mass to 5 via the Rigidbody.