How to set the parent of an instantiated game object
I'm working on a simple "space shooter" game. I have a player prefab a player script attached. The following code takes place within my update. //Activate Shield if (Input.GetKeyDown(shieldKeyCode)){ if (shieldOn == true) { } else { shieldOn = true; GameObject clone = Instantiate(shieldMesh, transform.position, transform.rotation) as GameObject; clone.transform.parent = gameObject.transform; } }
I had hoped that this would make the transform of my player prefab the parent of the shield mesh game object clone. However, when I run my game I get a "Null Reference Exception" error pointing to the final line of code.
I have tried using SetParent() to no avail as well.
End goal, I want the shield to instantiate upon key press, gaining a parent of the player's transform keeping the shield wherever the player is. As of right now it just instantiates a shield and leaves in where it was (while giving my NRE error).
Answer by AlmightyFork · Jul 24, 2016 at 12:17 AM
//Activate Shield
if (Input.GetKeyDown(shieldKeyCode)){
if (shieldOn == true)
{
}
else
{
shieldOn = true;
GameObject clone = Instantiate(shieldMesh, transform.position, transform.rotation) as GameObject;
clone.transform.parent = gameObject.transform;
}
Your answer
Follow this Question
Related Questions
Cannot Parent a Prefab Instantiated with Resource.Load() 1 Answer
reset a GameObject parents childs to 0 if a item has changed its parent 2 Answers
Can’t keep the position 0 Answers
Cannot set parent for instantiated GameObject. (Exception: Can't destroy Transform component of...) 0 Answers
How to set the transform.position of a GameObject after making it a child? 0 Answers