Is OnEnable fired right after Awake?

Scenario:

I have a View that’s supposed to subscribe to an event from a controller to update a Text.text with a score only if the score in the controller gets updated.

For this I make an event in my controller (called BattleInstance) and make my controller a singleton in Awake():

public event System.Action<int> UpdatedPoints;

private void Awake()
        {
            if (instance == null)
            {
                instance = this;
            }
            else if (instance != this)
            {
                Destroy(gameObject);
            }
        }

In my BattleViewController I want to make sure I subscribe and unsubscribe (Bye,Bye memleak :wink: ) in the OnEnable() and OnDisable()

private void OnEnable()
    {
        BattleInstance.instance.UpdatedPoints += this.UpdatePointDisplay;
    }

    private void OnDisable()
    {
        BattleInstance.instance.UpdatedPoints -= this.UpdatePointDisplay;
    }

Now when I run this I get this error

NullReferenceException: Object reference not set to an instance of an object BattleViewController.OnEnable () (at Assets/Scripts/BattleScene/ViewControllers/BattleViewController.cs:44)

when trying to subscribe because apparently the OnEnable in my ViewController is called before the Awake in my Controller. :frowning:

Subsequently of course, when my Controller fires the event in the Start() to initialize the score display as 0 I get:

NullReferenceException: Object reference not set to an instance of an object BattleInstance.Start () (at Assets/Scripts/Administration/BattleInstance.cs:38)

EDIT:

To specify my question(s):

  • Do I understand it correctly that the OnEnable is fired right after an object’s Awake? So the order being Object1.Awake() | Object1.OnEnable() | Object2.Awake() | Object2.OnEnabnle() | Object1.Start() | Object2.Start ?
  • How do I in my Object1.OnEnable() make sure that Object2 is Awake?

Hi, @quicksly

Yes OnEnable() is called after Awake()
Unity Function Execution Order

But you can change it by using the following,

ScriptExecutionOrder

The event is only fired the moment an item is enabled.