简体   繁体   English

Unity3d向菜单项中的对象添加RigidBody

[英]Unity3d Adding RigidBody To The Object in MenuItem

I write external script for Unity3d and I have one problem. 我为Unity3d编写了外部脚本,但有一个问题。 This problem is adding RigidBody to the object in MenuItem. 此问题是将RigidBody添加到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: 这是Unity3d日志:

MissingComponentException: There is no 'Rigidbody' attached to the "Cube" game object, but a script is trying to access it. MissingComponentException:“ Cube”游戏对象没有附加“ Rigidbody”,但是脚本正在尝试访问它。 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) UnityEngine.Rigidbody.AddForce(Vector3力,ForceMode模式)UnityEngine.Rigidbody.AddForce(单x,单y,单z)(位于C:/buildslave/unity/build/Runtime/Dynamics/ScriptBindings/Dynamics.bindings.cs: 171)CrossX.CubePhysButton(UnityEditor.MenuCommand menuCommand)(在Assets / Editor / CrossX.cs:68)

How do I solve this problem? 我该如何解决这个问题?

GameObject.CreatePrimitive creates a GameObject with a Mesh Renderer, Mesh Filter, and Collider. GameObject.CreatePrimitive创建带有网格渲染器,网格过滤器和对撞机的GameObject。 It does not add a RigidBody. 它不会添加RigidBody。 Simply add one yourself: 只需自己添加一个即可:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM