The question is answered, right answer was accepted
Instantiate an object as child
Hello,
I'm trying to make an overlay and i want to instantiate the hearts in the "Overlay" GameObject. I searched on Internet (i actually tried things found in the first two pages of google) but nothing works.
Here is my code :
 using UnityEngine;
 using System.Collections;
 
 public class Overlay : MonoBehaviour {
     public Transform CoeurPlein;
     public Transform CoeurVide;
 
     // Use this for initialization
     void Start () {
     
 
         GameObject TCoeurPlein = Instantiate (CoeurPlein, new Vector3 (0,0, 0), Quaternion.identity) as GameObject;
         TCoeurPlein.transform.parent = GameObject.Find("Overlay").transform;
 
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 }
 
And the error message :
NullReferenceException: Object reference not set to an instance of an object Overlay.Start () (at Assets/script/Overlay.cs:13)
Thanks
Answer by corn · Jan 10, 2016 at 04:30 PM
The error is there :
 TCoeurPlein.transform.parent = GameObject.Find("Overlay").transform;
The fact that there is a NullReferenceException on that line means that GameObject.Find("Overlay") returned null, so you're trying to access the transform of a null object. It appears that there isn't an "Overlay" GameObject in your scene.
When using methods the likes of Find, it's generally a good idea to check if it actually worked.
     void Start()
     {
         GameObject TCoeurPlein = Instantiate(CoeurPlein, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
         GameObject overlayParent = GameObject.Find("Overlay");
 
         if (overlayParent != null)
         {
             TCoeurPlein.transform.SetParent(overlayParent.transform);
         }
     } 
Thanks for the fast answer :)
I have this : 
I tried to find with tag, but that doesn't work . I tried to find with Find("$$anonymous$$ain Camera/Overlay") that doesn't work either, finding a new gameObject either (with name and tag).
GamObject.Find("Overlay"); works fine for me. $$anonymous$$ake sure you didn't make a typo, maybe your object is actually named "Overlay " (ending with a space), that'd be an easy mistake to overlook.
Evrything is ok with the overlay. I tried with the "if != null "and it got the print i put in it. So the probleme come from the instantiate object (TCoeurPlein). I tried it with the !=null and it doesn't get the print. Do you have any idea about this one?
Actually it looks like this :
 GameObject TCoeurPlein = Instantiate (CoeurPlein, new Vector3 (0,0, 0), Quaternion.identity) as GameObject;
 
         GameObject overlayParent = GameObject.Find ("Overlay");
         if (overlayParent != null) {
             TCoeurPlein.transform.SetParent(overlayParent.transform);
         }
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                