- Home /
Instantiating a new gameObject as a child of a different gameObject
here is the code public void FillNextOpenSpot()
{
GameObject newSelected = Instantiate (selected, openSpotPos, Quaternion.identity) as GameObject;
newSelected.transform.SetParent (nextOpenSpot.transform); // tried this patent
newSelected.transform.parent = nextOpenSpot.transform; // and tried this one too
}
nextOpenSpot is a game object that I have declared globally. The object is Instantiating but it's just going straight to the top of the hierarchy. One weird thing that I found in troubleshooting is that it will child to the object the code is attached to if I changed the right side of the assignment of either patent to just "Transform". It only doesn't work when I try to specify a different transform.
That would rather suggest that nextOpenSpot.transform is null. Have you tried adding a Debug.Log to verify that it is not?
Answer by RobAnthem · Dec 25, 2016 at 06:30 PM
Just to see if it changes anything, you could try
newSelected.transform.SetParent (nextOpenSpot.GetComponent<Transform>());
Omg thank you so much. You seriously just saved me so much stress. here's my finished script using that patent if you're interested
{
Transform newParent = nextOpenSpot.GetComponent<Transform> ();
GameObject newSelected = Instantiate (selected, openSpotPos, Quaternion.identity) as GameObject;
newSelected.transform.SetParent (newParent);
}
thanks a lot! Happy holidays my friend
Answer by jmgek · Dec 24, 2016 at 08:01 PM
It is transform.parent, I don't know where you're getting nextOpenSlot but it has to be a game object in the scene for it to be a parent:
GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
GameObject sphere2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere2.transform.parent = sphere.transform;
Your answer
Follow this Question
Related Questions
Creating new Transform from existing objects Transform to Instantiate object 1 Answer
Instantiate Terrain Object as child of Empty Game Object 1 Answer
Getting instance of an sub object rather than the original's subobject 0 Answers
Finding Children question 3 Answers
Instantiate object as child of exsisitng game object 1 Answer