【问题标题】:Unity: Prefab parenting in codeUnity:代码中的预制育儿
【发布时间】:2015-09-06 07:37:30
【问题描述】:

假设我想要多个名为childTile 的预制对象,它将另一个名为parentTile 的预制对象作为父对象。所以每当parentTile 旋转时,childTiles 将围绕parentTile 旋转。

基本上这是我写的:

public GameObject childPrefab;
public GameObject parentPrefab;

void Update()
{
   for(int i = 0; i < 10; i++)
   {
      GameObject clone = Instantiate(childPrefab, /*PsuedoCode: random position*/ , Quaternion.identity)

      clone.transform.parent = parentPrefab;

   }
}

预期的结果是在运行时,如果我在现场旋转parentPrefab,10 childPrefabs 也应该旋转。我尝试了很多方法,但都失败了,除非我在 Hierachy 栏上手动将childPrefabs 拖到parentPrefab。

【问题讨论】:

    标签: unity3d gameobject


    【解决方案1】:

    您确定要在每帧上Instantiate 10 个子预制件(Update 每帧调用一次)。

    我认为你的问题是,你没有 Instantiate 父预制件。

    如果我接受你的代码并修复它,它对我来说就像一个魅力。

    public GameObject childPrefab;
    public GameObject parentPrefab;
    
    void Start() 
    {
        GameObject parent = Instantiate(parentPrefab) as GameObject;
    
        for(int i = 0; i < 10; i++)
        {
            GameObject child = Instantiate(childPrefab) as GameObject;
            child.transform.parent = parent.transform;
        }
    }
    

    这是上面代码的结果,我怀疑这就是你想要的?

    【讨论】:

    • 非常感谢!!我没有实例化父对象。我真是太愚蠢了,我花了 4 个小时来解决这个问题。
    猜你喜欢
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多