I want to create an empty GameObject
that is a child of the Components GameObject
.
Example:
I have a simple spline and I am using the child objects as the control points. I have a button to add new control points which uses the following code to create a new object and should also set the new GameObject
as a child of the scripts object.
public void addNewNode()
{
var g = new GameObject();
g.transform.parent = this.transform;
}
This implementation does not work and does not show the object in the inspector which I assume means something went wrong and the object was destroyed.
Edit:
To test that setting parent was working properly I printed the name of g
parent transform. It printed the correct name so I think the problem is that setting the parent is not being reflected in the editor. NOTE: I am using a [CustomEditor()]
script in addition to the MonoBehaviour
script if this effects something with unity.
Edit 2 - Minimal Full Code:
[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);
}
or
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);
}