Error when I stop testing the game: MissingReferenceExeption

Hi!

I have a weird problem which I hope someone here could Un-weird a bit. I have an array of buttons which I occasionally loop through using a foreach statement. there are 25 buttons and they check for objects in a list and as long as there are objects in this list the buttons should activate untill they are as many buttons as elements in the list. So running the code when I have 8 objects in my list, 8 buttons are rendered and so on. In the foreach loop what essentially happens is that if theres another object in the list, activate the button and if not and a button is activated, deactivate it. So it could shrink back to like seven when needed. At the end of each run through the foreach loop, I call Debug.Log to print the number of buttons now enabled.

Okay, so everything works flawlessly and as I am testing it I have no errors and the game keeps running exactly as it should. However, as soon as I click stop, the debug window prints an error between all my Debug.Log prints. So during game i get the output:

1
2
3
4

But as soon as I click “stop” the output changes to:
1
MissingReferenceExeption…*
2
MissingReferenceExeption…*
3
MissingReferenceExeption…*
4
MissingReferenceExeption…*

Why does this happen when I click stop when its all working nice during play? Since its printed between my own logs I would think that the error comes mid-game but is somehow filtered away. But why now? An hour ago I had those errors during gameplay but they got fixed.

Otherwise the buttons really are working well. They all reference the objects in the list and using them works perfect.

*MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object

(I never call destroy on the object. I use button.gameObject.SetActive to enable and disable it)

Most likely, what is happening, is that the code is being run when the scene is shutting down. It deletes the objects, but if the code is still running, it’s expecting them to exist. One thing you could try is using the OnDestroy() function to unregister it from that buttons behaviour.

Honestly though, if you don’t see it till you stop the scene, it might not be anything to worry about, especially if that data is not needed for following scenes. It’s not clean by any means, but if it’s functional during normal use, and doesn’t crash the whole game, it may be more trouble than it’s worth.