我想创建一个空的
GameObject
,它是组件 GameObject
的子级。
示例: 我有一个简单的样条线,我使用子对象作为控制点。我有一个添加新控制点的按钮,它使用以下代码创建一个新对象,并且还应该将新的
GameObject
设置为脚本对象的子对象。
public void addNewNode()
{
var g = new GameObject();
g.transform.parent = this.transform;
}
此实现不起作用,并且不在检查器中显示对象,我认为这意味着出现问题并且对象被破坏。
编辑:
为了测试设置父级是否正常工作,我打印了
g
父级转换的名称。它打印了正确的名称,所以我认为问题是设置父项没有反映在编辑器中。注意:除了 [CustomEditor()]
脚本之外,我还使用 MonoBehaviour
脚本(如果这会影响统一)。
编辑 2 - 最小完整代码:
[CustomEditor(typeof(SplineManager))]
public class SplineManagerInspector : Editor {
public override void OnInspectorGUI()
{
SplineManager spMngr = (SplineManager)target;
// additional code to add public variables
if (GUILayout.Button ("Add New Node")) {
spMngr.addNewNode ();
EditorUtility.SetDirty (target);
}
// code to add some public variables
if (GUI.changed) {
spMngr.valuesChanged ();
EditorUtility.SetDirty (target);
}
}
}
[RequireComponent (typeof(LineRenderer))]
public class SplineManager : MonoBehaviour
{
public SplineContainer splineContainer = new SplineContainer ();
public LineRenderer lineRenderer;
private GameObject gObj;
// additional code to deal with spline events/actions.
public void addNewNode ()
{
Debug.Log ("new node");
gObj = new GameObject ();
gObj.transform.parent = this.gameObject.transform; // this does not work... (shows nothing)
}
}
public void addNewNode( GameObject parentOb)
{
GameObject childOb = new GameObject("name");
childOb.transform.SetParent(parentOb);
}
或
private GameObject childObj;
private GameObject otherObj;
public void addNewNode()
{
childObj = new GameObject("name");
// in case you want the new gameobject to be a child of the gameobject that your script is attached to
childObj.transform.parent = this.gameObject.transform;
// we can use .SetParent as well
otherObj.transform.SetParent(childObj);
}
Instantiate
。它具有一个采用父级的构造函数。
GameObject newChild = Instantiate(new GameObject("My new child object"), this.transform);