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.