How can I create empty game object and attach new components to it in script?

When I click a button , I want to create an empty game object in the scene , and create a mesh component , mesh render component at the same time . Then attach the mesh component / mesh render component to the new object.
I have just found the method :
GameObject.CreatePrimiteve( … ) , which can just create primitives .
It’s not what I want.

var object = new GameObject("Empty", MeshFilter, MeshRenderer);
object.GetComponent(MeshFilter).mesh = myMesh;

–Eric

1 Like

Thx , Eric , but I use CSharp , how to do the same thing with csharp code ?
And go further more , how can I make one game objet be another’s child ?
In editor, I can easily drag and drop one object on another to make them child and parent .
In script , the correspond api can not be found easily .
So how to ?

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {
  	private GameObject go;
	private Mesh myMesh;
	
	void Update () {
	 go = new GameObject("Empty");
	go.AddComponent("MeshFilter");
    go.AddComponent("MeshRenderer");
	myMesh = go.GetComponent<MeshFilter>().mesh;
	}
}

That should work. I haven’t tested it though.

1 Like

KingCharizard THX,
The second question remains ,
In script ,how can I make one game objet be another’s child ?
transform plays an important role of the relationship , below seems to be no use:

a.transform.parent = b.transform.

More should be done to finish this , what are they?

It is quite simple.
just remember that the parent is not an object but transform component of object.

private GameObject parentObject;
private GameObject childObject;
void Start()
{
      parrentObject.transform.parent = childObject.transform
}

Alternatively you can use the Transform.SetParent method. It is useful in that it can original position, scale and rotation may remain so as it was (aka. Not relative to the parent)

The code he posted in his last reply worked fine, he was probably confused because the position didn’t change when he did it. Of course, it won’t, unless you use SetParent (which didn’t exist at the time) with a “false” value for the optional worldPositionStays parameter, or manually reset the position to zero after re-parenting it. Sadly, we’ll never know, because he hasn’t been on this site in four years.

Please don’t necro posts unless you have a good reason- there are literally thousands of posts where re-parenting objects is explained, and I doubt this guy in particular cares anymore.

Ok, thanks for information :slight_smile: