Search Unity

Question Monobehaviour doesn't call Awake after recompile

Discussion in 'Scripting' started by jjiangweilan, Jul 9, 2021.

  1. jjiangweilan

    jjiangweilan

    Joined:
    Mar 31, 2018
    Posts:
    19
    Hi, I need to initialize some non-serializable variables in my script. And because they are private to the script, I initialize the variable in Awake function as Unity recommends. Everything is fine until I change any code and Unity recompiles. The non-serialized variables are lost because I believe Awake function is not called after recompile and Unity can only reset the serialized variables.

    I used to solve this by lazy initialization or put them in OnEnable (You need to check if the the variable is initialized), but neither way is elegant solution for simply variable initialization.
     
  2. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Wait, do you mean change code while you're in play mode in the editor?
     
  3. jjiangweilan

    jjiangweilan

    Joined:
    Mar 31, 2018
    Posts:
    19
    No. Just in editor mode
     
  4. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Uhh, awake is called every single time you start the game. To be more precise it's ran at the first frame of an objects existence right after construction.
    I don't exactly understand your issue it seems
     
  5. jjiangweilan

    jjiangweilan

    Joined:
    Mar 31, 2018
    Posts:
    19
    Sorry I miss the key point here. The script needs to be "ExecuteAlways".

    Code (CSharp):
    1. [ExecuteAlways]
    2. public class Foo : MonoBehaviour
    3. {
    4.     private Bar bar;
    5.  
    6.     private void Awake()
    7.     {
    8.         bar = new Bar();
    9.     }
    10. }
    If you have a script like this, the Awake function won't be called after recompile, it makes any other code that depends on bar throws an error.
     
  6. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Well first and foremost, throw a Debug.Log() in there and make sure it's being called.

    Secondly, are you sure this is the best way to accomplish what you're looking for? Unity gets to decide when and how [ExecuteAlways] version of these functions are called, so having a chain of order dependencies seems like a bad idea.
     
  7. gorbit99

    gorbit99

    Joined:
    Jul 14, 2015
    Posts:
    1,350
    Use OnEnable for this, that's the usual method for this
     
    jjiangweilan likes this.