Search Unity

  1. New Unity Live Help updates. Check them out here!

    Dismiss Notice

Multi-Scene Editing & GameObject.Find

Discussion in 'Scripting' started by rarebyte, Jan 25, 2016.

  1. rarebyte

    rarebyte

    Joined:
    Sep 26, 2015
    Posts:
    10
    Example:
    So I have my game-logic in scene A, and my UI in scene B. At the start of the game I use SceneManager.LoadScene(..., LoadSceneMode.Additive); to load both scenes into the game.
    Now how do I find a game-object that's in scene B from a script that's in scene A? The simple GameObject.Find doesn't seem to work in this case.

    Thanks and cheers.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    7,322
    It sounds like GameObject.Find may be broken, but rather than fix that, let's ditch GO.F entirely. You'll be better off - GameObject.Find is terrible in many ways.

    Seems like you need your in-game object and menu to communicate with each other. Use a singleton for your menu and/or player in that case:

    Code (csharp):
    1. public class SomeClass : MonoBehaviour {
    2. public static SomeClass instance;
    3. void Awake() {
    4. instance = this;
    5. }
    6. public int whatever;
    7. }
    8.  
    9. // anywhere else
    10. SomeClass.instance.whatever = 5;
    11.  
     
    Rodolinc likes this.
  3. SteenLund

    SteenLund

    Unity Technologies

    Joined:
    Jan 20, 2011
    Posts:
    481
    Hi,

    StarManta is right, try to avoid GameObject.Find. That said, Find() should work across all scenes, can you share some example code of it not working?

    Be aware though that you cannot Find() the object immediately after calling LoadScene, you have to wait one frame for the scene to finish loading.
     
    Harinezumi likes this.
  4. Harinezumi

    Harinezumi

    Joined:
    Jan 7, 2013
    Posts:
    49
    Thank you, even though I did wait one frame, I didn't realise that the scene in which I was trying to find has not yet finished loading when I was trying to call Find().
     
    Ziplock9000 likes this.
unityunity