C# Question About Instantiating Child Objects

Hello friends

I am having a small problem figuring out what I should be looking for in regards to what I am trying to do. Feel free to share some code or just point me in the right direction :slight_smile:

My problem involves a number of child objects laid out as a grid, each child grid object has its own child objects that are not instantiated. I have it so each grid square will be selected on a click and open a GUI element with a list of possible children to spawn. How would I go about spawning said children of the object and ensuring they spawn directly overtop the parent.

Thanks

first Instantiate the child object, then set it’s parent using object.transform.parent (see here) to make it a child of the object. then set its local position to 0,0,0 so that it will be in the center of the parent (then adjust the local position as needed).

Here’s some sample code:

	private void InstantiateMyGameObject(GameObject obj){
		GameObject instantiated = Instantiate(obj);			//instantiate the object
		instantiated.transform.parent = this.transform;//assuming this script is attatched to the desired parent
		instantiated.transform.localPosition = Vector3.zero;//reset the local position, moving it to the center of the parent
	}