- Home /
Instantiating a gameObject then setting its parent during runtime
I have seen similar questions to this and tried them but they didnt work for me.
I have a simple gui in my demo, when a button is pressed another obstacle is supposed to appear at a random position. Onscreen there are already several obstacles, these are all children of the parent "Obstacles". I would like to spawn another obstacle when the button is pressed and have it appear underneath Obstacles in the hierarchy. When i try the below code the obstacle is created however it is not a child, just a gameobject on its own.
Instantiate(obstacle, randomPos, Quaternion.identity);
obstacle.transform.parent = parentObstacles.transform;
I have tried transform.setparent aswell, with the same results. Is there anything else I can try? I'm using Unity 5, is this the problem?
Answer by AlwaysSunny · Apr 02, 2015 at 05:37 PM
You are misunderstanding how to instantiate objects. Unless you know exactly what you're doing and why, you should:
Expose a myPrefab variable, populated in the inspector...
Never write to or change myPrefab with scripting...
Instantiate the myPrefab object....
Do not treat the new instance as if it's myPrefab, but an instance thereof....
GameObject prefabInstance = Instantiate( myPrefab, pos, rot ) as GameObject;
prefabInstance.transform.parent = whatever;
Sorry for the late reply, was on holidays! Thanks for the response, works prefectly! Just incase anyone needs this in the future, an error will occur unless you have whatever.transform. Ty AlwaysSunny :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613191948im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Manipulating Instanced Object 2 Answers
Parent object to child of another? 1 Answer
How to make multiple gameobjects child of one and the same transform (SCRIPT) 2 Answers