- Home /
Set parent of instantiated object.
Hi, I'm trying to instantiate an object and then set the parent. This is my code (it's in an OnTriggerEnter void btw :-) )
GameObject healthgameObject = Instantiate(health, m1_enemy1_healthSpawn.transform.position, m1_enemy1_healthSpawn.transform.rotation) as GameObject;
healthgameObject.transform.parent = m1_enemy1_healthSpawn.transform;
It gives no errors when I look in the console, but when I play the game and my player hits the object it pauses the game and gives me this error:
Object reference not set to an instance of an object
At this line: healthgameObject.transform.parent = m1_enemy1_healthSpawn.transform;
How can this be solved?
Thanks, Andreas.
This would happen if 'health' is not initialized. If you did not drag and drop a game object on 'health' in the inspector or if your GameObject.Find() or GameObject.FindWithTag() did not find the specified game object.
It is possible this script is attached to more than one game object, and you did not initialize all of them?
Well, In runtime everything is assigned, but when the player hit's the other object, the error comes. (It also says that the error comes from the gameObject the script is attached to, so I don't think it's attached to anything else). The script is also attached to the player :-)
On the top right of the Hierarchy window there is a place to type a search term. Type in the name of the script. Then check each game object with the script to verify that value is initialized.
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
Instantiated GameObject collision without script repetition? 1 Answer
parenting instantiated object 2 Answers