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

How to reference a gameobject in different scene

Discussion in 'Scripting' started by MitjaHD, Dec 5, 2019.

  1. MitjaHD

    MitjaHD

    Joined:
    Sep 30, 2018
    Posts:
    64
    When I click on the button, I want to set some values to a gameobject in another scene and then load that scene. I tried using Gameobject.Find, but it returns NullReferenceException. I tried using DontDestroyOnLoad before loading to second scene, but it still doesn't find it.
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    You can't Find GameObjects which don't exist in the hierarchy, and objects in not yet loaded scenes aren't in the hierarchy yet. There are a few typical approaches:

    * Load the new scene additively, then Find the GameObject as you are already trying (using a tag instead of the GameObject's name is a slightly better approach by the way)
    * Use a GameObject with DontDestroyOnLoad set, then load the new scene. When the new scene loads have the GameObject you want to set the values on find this DontDestroyOnLoad object and get its initialization values from it.
    * Pass the values in static variables, which aren't affected by scene loads and aren't associated with GameObjects anyways.

    Google for DontDestroyOnLoad, additive scene loading, and static variables for more information on each topic.
     
  3. MitjaHD

    MitjaHD

    Joined:
    Sep 30, 2018
    Posts:
    64
    I guess that the problem is that this object is a child of two other objects, but if I use dontdestroyonload then the whole scene stays the same.
     
  4. xCeas

    xCeas

    Joined:
    Mar 31, 2013
    Posts:
    50
    +1 for use DontDestroyOnLoad, if you have GameObjects which you need to reference from a different scene, they probably are a Utility or a StateManager in both cases you want the object to be persistent.

    DontDestroyOnLoad - simply means that when you switch scenes said object won't be deleted and maintain the data it holds (meaning no re-initialization as well).

    Hope this helps