1

我想创建一个空的GameObject,它是 Components 的子级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)
    }
}
4

1 回答 1

1
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);
}
于 2017-10-05T18:27:09.367 回答