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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

GameObject.Find() error

Discussion in 'Scripting' started by aidanseeberg, Jul 18, 2015.

  1. aidanseeberg

    aidanseeberg

    Joined:
    Jul 10, 2015
    Posts:
    26
    SetDifficulty = GameObject.Find("DifficultySlider").GetComponent<Slider>().value;

    if (SetDifficulty == 1)
    {
    GameObject.Find("Manager").GetComponent<DropSpawning1>().spawnCooldown1 = 0.20f;
    GameObject.Find("_Constant").GetComponent<DropSpawning>().spawnCooldown = 0.20f;
    }
    if (SetDifficulty == 2)
    {
    GameObject.Find("_Constant").GetComponent<DropSpawning>().spawnCooldown = 0.125f;
    GameObject.Find("Manager").GetComponent<DropSpawning1>().spawnCooldown1 = 0.125f;
    }
    if (SetDifficulty == 3)
    {
    GameObject.Find("_Constant").GetComponent<DropSpawning>().spawnCooldown = 0.05f;
    GameObject.Find("Manager").GetComponent<DropSpawning1>().spawnCooldown1 = 0.05f;
    }



    For some reason this code keeps giving me an error message that reads :
    NullReferenceException: Object reference not set to an instance of an object
    ButtonManager.Update ()
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    So either it can't find the object or it can't find the DropSpawning/DropSpawning1/Slider component on the object it that it does find. We can't really help with that - it should tell you what line gives you the error to help point you in the right direction.
     
  3. aer0ace

    aer0ace

    Joined:
    May 11, 2012
    Posts:
    1,511
    Also, a line number alone may not help determine whether it's the object or the component since you're dereferencing twice in the same line. Break up the code and see where it errors, or better yet, run it in the debugger and see what's going on?
     
  4. aidanseeberg

    aidanseeberg

    Joined:
    Jul 10, 2015
    Posts:
    26
    It is now talking about the line that looks for the "Manager" GameObject. I might have a solution, does it matter that "Manager" is in another scene than this script itself?
     
  5. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Yes. GameObject.Find can only find objects that are currently in the scene hierarchy.