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

using Objects.DontDestroyOnLoad(this);

Discussion in 'Scripting' started by fredyyanez, Jul 17, 2015.

  1. fredyyanez

    fredyyanez

    Joined:
    Jul 8, 2014
    Posts:
    33
    I have 4 scenes in my project. I create a master controller that has a script attached to it.
    The controller is in the hierarchy in the first scene but it is not in the rest of the scenes.
    When I switch from scene 1 to scene 2 The game object is now in the hierarchy( of scene 2) but it is not there when I am coding it (not running the project). How do I access this object in the rest of the scenes considering it in not in the hierarchy until the project is ran?


    Thanks,

    Alfredo
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    There are quite a few different ways, two quick and easy ways would be using static variables or calling Object.FindObjectOfType<MasterController>()
     
  3. fredyyanez

    fredyyanez

    Joined:
    Jul 8, 2014
    Posts:
    33
    I see, the object that has the script is an empty GameObject, so what would the parameter for this function be?

    Also I have a tag on that object, can i find it with the tag too?
     
  4. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Check out the docs for GameObject and scroll down to the Static Functions section with all of the "Find..." methods. You can find GameObjects a lot of different ways, including by tag.
     
  5. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    ^ Yes that ^


    You don't need a parameter for Object.FindObjectOfType<MasterController>(), however, you could also find it with Object.FindObjectOfType("MasterController"). The difference is that the first way will return a reference to the MasterController component, and the second way will return a reference to the GameObject that has the MasterController component.