0

在我的Unity3D项目中,我得到了GameObject一辆卡车的综合体,他的层次结构看起来像这样。

+ Truck
   +FrontPivotPoint
      +LeftWheel
        Tire
        Rim
        Hindge
      +RightWheel
        Tire
        Rim
        Hindge
    +CenterPivotPoint
      +Body
        Arm
        Screw
        Pin  

基本上发生的事情是我有很多复杂的养育方式,我想深入每个孩子并为他添加一个RigidBody. 我认为它应该是嵌套的,但我没有什么想法。任何帮助,将不胜感激!

4

3 回答 3

1

Unity3d 允许您轻松地自动化每个例程。您可以考虑添加自定义菜单项。

public class MakeRigidBodies : EditorWindow
{
  [MenuItem ("Make rigid bodies %&r")]
  private static void Execute()
  {
    var selectedObject = UnityEditor.Selection.activeObject;
    if( selectedObject && selectedObject is GameObject )
    {
       // for all children of selectedObject
       {
         // add rigid body
       }
    }
  }
}
于 2014-08-19T10:32:55.327 回答
1

从我所见,你的游戏对象的结构就像一个树数据结构。卡车作为其父/根节点,其他作为其子节点。因此,您必须使用树遍历算法遍历结构中的所有对象/节点,我所知道的最好的是深度优先搜索(DFS)算法。

DFS 像嵌套循环一样工作,主要算法是:

  1. 从根节点开始
  2. 找到它的节点子节点
  3. 拜访孩子
  4. 返回第 2 步,直到所有孩子都被访问

该算法可以在 Unity3d 中实现,因为GameObject它的子信息存储在变换属性中(参见http://answers.unity3d.com/questions/416730/get-the-child-gameobject-of-a-parent-and-not-the -t.html )。最后,我们可以添加RigidBodywithGameObject方法AddComponent()(参见http://answers.unity3d.com/questions/19466/how-do-i-add-a-rigidbody-in-script.html)。

这是我回答您问题的脚本:

using UnityEngine;
using System.Collections;

public class AddRigidBody : MonoBehaviour { 
    private void addRigidBody(GameObject gameObject)
    {
        Rigidbody rigidBody = gameObject.AddComponent<Rigidbody>();
        foreach(Transform t in gameObject.transform)
        {
            addRigidBody(t.gameObject);
        }
    }

    void Start () {
        addRigidBody (this.gameObject);
    }
}

此脚本附加到 parent/root GameObject。该AddRigidBody()方法在此脚本启动时调用(如Start()方法中),该方法将遍历所有子项并RigidBody通过它添加一个。

于 2014-08-19T13:53:15.210 回答
0

如果我没记错的话,请耐心等待,因为我使用 Unity3D 已经有一段时间了,这可以解决它:

* Drag your model onto the stage
* Your entire model should now be selected; parent and its underlying children
* Select the option to add a rigidbody and it should add it to all selected objects.
* Make a prefab of the model and you should be done.

再一次,不要相信我。已经有一段时间了,因为我现在无法访问 Unity3D,所以我自己无法检查此方法。

如果这是您想要的代码方法,请尝试以下方法(C#,Boo 或 Java 的方法可能会有所不同):

生孩子: http: //forum.unity3d.com/threads/get-child-c.83512/(见第二个回复)添加刚体:http ://answers.unity3d.com/questions/19466/how-do -i-add-a-rigidbody-in-script.html

我希望这有帮助。

于 2014-08-19T10:10:46.857 回答