【问题标题】:How to set new GameObject as child of Components GameObject?如何将新游戏对象设置为组件游戏对象的子对象?
【发布时间】:2017-10-05 18:08:43
【问题描述】:

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

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

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

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

编辑:

为了测试设置 parent 是否正常工作,我打印了 g parent 转换的名称。它打印了正确的名称,所以我认为问题在于设置父级没有反映在编辑器中。注意:除了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)
    }
}

【问题讨论】:

  • 请在发布此类问题之前调试您自己的代码。将Debug.Log 放入该函数中,看看它是否出现。删除 g.transform.parent = this.transform; 并查看新创建的对象现在是否在 Hierarchy 选项卡中可见。最好为新创建的对象命名,以便您可以轻松找到它var g = new GameObject("THE NAME");
  • 您当前的脚本应该这样做。我建议你试试SetParent 函数,看看会发生什么。如果这也不起作用,那么您应该准确发布完整的代码 + 它所附加的 GameObject 的 Inspector 选项卡屏幕截图以及单击“Run”时该 GameObject 的 Hierarchy 选项卡。
  • @Programmer 我已经添加了少量代码来显示使用的类/函数的结构。

标签: c# unity3d gameobject unity3d-editor


【解决方案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);
}

【讨论】:

  • 我建议使用SetParent() 方法。
  • link 看看这个并确保你的方向符合预期。
  • 这个答案其实是正确的。我有一个错误,我检查了是否更改了删除子项的值。长话短说,这个解决方案效果很好。
  • 嗯,我很高兴它帮助了伴侣:)
猜你喜欢
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
相关资源
最近更新 更多