0
votes

I write external script for Unity3d and I have one problem. This problem is adding RigidBody to the object in MenuItem. Here's my code:

[MenuItem("NewTool/Physics/Cube (RigidBody)", false, 10)]
static void CubePhysButton(MenuCommand menuCommand) {

    GameObject gameCubePhys = GameObject.CreatePrimitive(PrimitiveType.Cube);
    Rigidbody cubePhys = gameCubePhys.GetComponent<Rigidbody>();
    cubePhys.AddForce(1, 1, 1);
    GameObjectUtility.SetParentAndAlign(gameCubePhys, menuCommand.context as GameObject);
    Undo.RegisterCreatedObjectUndo(gameCubePhys, "Create " + gameCubePhys.name);
    Selection.activeGameObject = gameCubePhys;


}

Here is Unity3d log:

MissingComponentException: There is no 'Rigidbody' attached to the "Cube" game object, but a script is trying to access it. You probably need to add a Rigidbody to the game object "Cube". Or your script needs to check if the component is attached before using it. UnityEngine.Rigidbody.AddForce (Vector3 force, ForceMode mode) UnityEngine.Rigidbody.AddForce (Single x, Single y, Single z) (at C:/buildslave/unity/build/Runtime/Dynamics/ScriptBindings/Dynamics.bindings.cs:171) CrossX.CubePhysButton (UnityEditor.MenuCommand menuCommand) (at Assets/Editor/CrossX.cs:68)

How do I solve this problem?

1
If you're interested in the source of the problem in the log: In your code, you used GetComponent<Rigidbody>() rather than AddComponent<Rigidbody>(). This means you are trying to retrieve something that isn't there, just like the log points out :) - Reckless Engineer
Also, let me direct your attention to gamedev.stackexchange.com, where the users are more geared towards answering this type of question (not that stack overflow is the wrong place, just the game dev site is even better). - Ed Marty

1 Answers

3
votes

GameObject.CreatePrimitive creates a GameObject with a Mesh Renderer, Mesh Filter, and Collider. It does not add a RigidBody. Simply add one yourself:

GameObject gameCubePhys = GameObject.CreatePrimitive(PrimitiveType.Cube);
Rigidbody cubePhys = gameCubePhys.AddComponent<Rigidbody>();