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

Do action when scene loads

Discussion in '2D' started by game_dev23, Jul 15, 2020.

  1. game_dev23

    game_dev23

    Joined:
    Aug 11, 2018
    Posts:
    10
    So I have a persistent game manager which exists in the first scene and stays throughout the scenes with DontDestroyOnLoad(); What I want to do is when a level loads I want to find certain UI elements with GameObject.Find() and update those according to player health.. etc. I have an OnSceneLoad function similar to this https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html in Awake(). However, when I search for the object, for one frame, it displays an error that the object is not found. How do I make my script wait until the level is done loading then find objects()?
     
    Last edited: Jul 15, 2020
  2. Wezai

    Wezai

    Joined:
    Dec 30, 2016
    Posts:
    74
    game_dev23 likes this.
  3. Raial

    Raial

    Joined:
    May 2, 2017
    Posts:
    24
    Why you don't use Awake() in the UI elements?
    I would put a script in the UI canvas with references to the child elements that need to be updated, and in the Awake() I would communicate with the GameManager so as to ask for the values.

    This way you also avoid GameObject.Find() (terrible for performance).
     
    game_dev23 likes this.
  4. game_dev23

    game_dev23

    Joined:
    Aug 11, 2018
    Posts:
    10
    Thanks for the advice. But how would I communicate that info with the gameManager?
     
  5. Raial

    Raial

    Joined:
    May 2, 2017
    Posts:
    24
    A method in the gameManager that returns an updated array of strings, and when you call it from your canvas you'll be able to update the text accordingly. There are practically infinite solutions to a problem when programming, try thinking your own too;)
     
    game_dev23 likes this.
  6. game_dev23

    game_dev23

    Joined:
    Aug 11, 2018
    Posts:
    10
    Thanks!