Null reference exception after trying to unsubscribe method in OnDisable()

I’m trying to unsubscribe method from the event, because I heard it’s very important to not forget doing this to prevent serious problems later, everythings works during the playtime, but sometimes it throws null reference exception after scene stop (I wrapped it with Debug.LogError for clarity). Is this ok?

private void OnEnable()
    {
        FindObjectOfType<Player>().HealthChanged += OnHealthChanged;
        _hearts = FindObjectsOfType<HeartUI>();
        Array.Sort(_hearts);
    }

    private void OnDisable()
    {
        var player = FindObjectOfType<Player>();
        if (player != null)
            player.HealthChanged -= OnHealthChanged;
        else
            Debug.LogError("PLAYER IS NULL!!!");
    }

OnDisable is called very late in the order of execution for a GameObject. By the time it is called, your Player object may have already been destroyed. If you want to empty the event, you can clear it in the Player object’s own OnDisable with this: HealthChanged = null.

This is very helpful, thanks.

@Lekret for more about what Stevens means above, check this:

Here is some timing diagram help:

Shows you the full lifecycle of MonoBehaviors. I find it handy to keep close by.

1 Like

Same here. It’s also such a monstrosity that I find it frightening to keep close by, but one must be brave about such things.

1 Like

Thanks.