【问题标题】:How to instantiate a prefab as a child of another object in Unity 5.3?如何在 Unity 5.3 中将预制件实例化为另一个对象的子对象?
【发布时间】:2016-04-22 12:28:40
【问题描述】:

我已经尝试过这段代码,但它会生成 NullPointerException。

o.transform.parent =gameObject.transform;

与此相同:

o.transform.parent =gameObject.transform;

我也试过这个:

public Transform body;
//inside a function:
GameObject o = Instantiate(entry, new Vector3(addX*x+startX, addY*y+startY, 0), Quaternion.identity) as GameObject;
o.transform.parent = body;

我也试过上面的代码,但最后一行改成这样:

o.transform.parent = body.transform;

【问题讨论】:

  • 哪个对象为空?
  • 没说。这是错误消息:NullReferenceException: 对象引用未设置为对象 StudentListController.FillList (System.String strList) 的实例(在 Assets/Scripts/StudentListController.cs:44)StudentListController+c__Iterator5.MoveNext ()(在资产/脚本/StudentListController.cs:23)
  • 第 44 行代码如下:o.transform.SetParent (body.transform);
  • 我已经尝试过切换该行,就像我上面提到的代码一样。
  • 实例化对象为空

标签: c# unity3d scripting


【解决方案1】:

你可以使用SetParent方法

 o.transform.SetParent(newParent);

【讨论】:

  • 也试过这个方法。我也尝试使用 newParent.transform 而不是 newParent 。同样的错误。
  • 实例化对象为空。我不明白为什么,因为它已根据我的层次结构成功创建
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-13
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
相关资源
最近更新 更多