Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Getting Null Reference Exception when referencing instantiated GameObject

Discussion in 'Scripting' started by daniobey46, Mar 15, 2023.

  1. daniobey46

    daniobey46

    Joined:
    Aug 25, 2021
    Posts:
    3
    Description:

    Hi,

    I'm currently working on a Unity project and I'm having trouble with referencing an instantiated GameObject in one of my scripts. I've tried using GameObject.Find() and GameObject.FindGameObjectWithTag() methods in the Start() method of my script, but I keep getting a null reference exception when trying to access the GameObject.

    Here are the things I've checked so far:

    • I've made sure that the name or tag of the GameObject is spelled correctly and matches the actual name or tag of the GameObject.
    • I've adjusted the script execution order to ensure that the script that instantiates the GameObject is executed before the script that references it.
    • I've checked if the GameObject is being destroyed after it is instantiated.
    • I've checked if the reference variable is public and assigned in the Inspector.
    • I've checked if there are multiple instances of the same GameObject.
    Despite these checks, I'm still getting a null reference exception. I'm not sure what else to do at this point. Can anyone offer any suggestions or advice on what else I can try to fix this issue?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    Show your code.
     
    Bunny83 likes this.
  3. FrankvHoof

    FrankvHoof

    Joined:
    Nov 3, 2014
    Posts:
    258
    As stated above; please show your code.
    Instantiate will return the newly spawned object. You can use that reference if needed. If your GameObject.Find()-Methods are returning null, you're usually either calling GameObject.Find() before the object was spawned, or after it's already been destroyed (or it's Inactive, in which case GameObject.Find() will also skip it).
     
  4. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    637
    This. You really shouldnt have to use Find() at all. You know where it is when you instantiated it.
     
    Kurt-Dekker likes this.