如何将新游戏对象设置为组件游戏对象的子对象?

How to set new GameObject as child of Components GameObject?

我想创建一个空的 GameObject,它是组件 GameObject 的子项。

示例: 我有一个简单的样条曲线,我使用子对象作为控制点。我有一个添加新控制点的按钮,它使用以下代码创建一个新对象,并且还应该将新的 GameObject 设置为脚本对象的子对象。

public void addNewNode()
{
   var g = new GameObject();
   g.transform.parent = this.transform;
}

这个实现不起作用,也没有在检查器中显示对象,我认为这意味着出了点问题,对象被销毁了。

编辑:

为了测试父级设置是否正常工作,我打印了 g 父级转换的名称。它打印了正确的名称,所以我认为问题是设置父级没有反映在编辑器中。注意:除了 MonoBehaviour 脚本之外,我还使用了 [CustomEditor()] 脚本,如果这会影响统一。

编辑 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);
}