我想创建一个空的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)
}
}
答案 0 :(得分:0)
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);
}