Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Slider OnValueChanged fires before Awake?

Discussion in 'UGUI & TextMesh Pro' started by Gordon_G, Dec 13, 2020.

  1. Gordon_G

    Gordon_G

    Joined:
    Jun 4, 2013
    Posts:
    372
    Hey all, I'm using Unity 2019.4.11f1.

    In a prefab that contains a slider I have a script and in that script I am caching a reference to singleton in Awake (only to improve the readability the code, I have many long lines of code that access the singleton).

    I also have the slider referenced in the script, and the slider's OnValueChanged event is linked to a function that contains the cached singleton variable and subsequently uses it to call a function.

    The prefab is already in the scene.

    The thing is, Awake shows that it finds the singleton and sets the cache variable, but when the game first runs there is a call to the slider's OnValueChanged event where the variable is null, only at the start. From there on the variable in the OnValueChanged function references the singleton properly.

    So clearly the slider event is firing before Awake. I thought Awake was supposed to run before anything else, so what gives?

    if you want to visualize:
    Code (CSharp):
    1. public GameEventManager gE;
    2.  
    3.    private void Awake() {
    4.        gE = GameEventManager.current;
    5.        // debugger shows gE has correct value
    6.    }
    7.  
    8.    // called by OnValueChanged:
    9.    public void SetGameSpeed( System.Single speed ) {
    10.        if( gE != null ) gE.DebugGameSpeedFactor( speed );
    11.        // debugger shows gE is null when the game first runs
    12.        // the easy fix is to put the null check in here so OK, but why?
    13.    }