Instantiate 在场景根中创建多个(不需要的)游戏对象副本

Instantiate creates multiple (unwanted) copies of game object in scene root

我有一个 GameObject.Instantiate() 方法可以创建 Page 游戏对象。 Page 游戏对象然后有一个 Start() 方法,它还实例化了一些新的游戏对象。

我的问题是在 Start() 方法中创建的游戏对象被创建了两次。首先,它被创建为 Page 游戏对象的子对象(我想要的,它工作正常),但随后它也在场景的根目录中创建了相同的游戏对象。

我尝试将 Debug.Log("Calling start method...") 添加到 Start() 以查看该方法是否被调用了两次,但情况似乎并非如此。它将文本输出到日志两次。

Navigation.cs

void navigateTo(Page page) {
    ...
    // Here we instantiate the Page.
    this.currentPage = GameObject.Instantiate (page.gameObject, this.content.transform).GetComponent<Page>();
}

Page.cs

void Start () {
    // Here we create a child GameObject. This get's created both as a child of 
    // the Page game object, but also in the root of the scene.
    GameObject tableGO = new GameObject ("Table");
    GameObject instance = GameObject.Instantiate(tableGO, this.gameObject.transform) as GameObject;
    ...
}

问题是 new GameObject ("Table") 创建了一个没有父对象的游戏对象,GameObject.Instantiate(tableGO, this.gameObject.transform) as GameObject; 也创建了一个游戏对象,但在第二种情况下,您使用第一个游戏对象作为模板(或类似预制件)并且给它设置一个父对象。因此,您可以删除 GameObject tableGO = new GameObject ("Table"); 并使用预制件创建游戏对象或删除第二行并将 tableGO.transform.parent 设置为您需要的任何值。