How do I add a rigidbody in script?

Hi,

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: http://unity3d.com/support/documentation/ScriptReference/GameObject.AddComponent.html

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.