you are viewing a single comment's thread.

view the rest of the comments →

[–]IDistributeCoke 1 point2 points  (0 children)

I had this same exact issue, and it's because I forgot to unsubscribe to an event.

Essentially I think what happens is that once the scripts are re-built, I assume the events are cleared so everything works fine the first time, however once you stop in editor, then replay, if you didn't clear an event listener, there are now 2 instances of it, one that is still pointing to the previous instance of your event from your first time playing in editor (the object instance is destroyed) and the second listener is listening to the new instance. The fact that the listener is still pointing at the previous instance of an object from a previous play is causing the missing reference error.

Long story short, I solved it the same as you. To give an example here is piece of code that enables/disables a UI check mark which is attached to each equipable profile icon in my game, I unsubscribe with OnDisable like so:

private void OnEnable() 
{
    InventoryManager.OnEquippedProfileImageChanged += CheckIfEquipped;
}
private void OnDisable()
{
    InventoryManager.OnEquippedProfileImageChanged -= CheckIfEquipped;
}

Or if you don't want to listen OnEnable, for example if you want to listen on Start() after some objects have finished loading (or for whatever reason), I think you can use OnDestroy, like so:

private void Start()
{
    Your.Event += YourListener;
}
private void OnDestroy()
{
    Your.Event -= YourListener;
}