General practices.

I’m kind of new to Unity development and not sure on general practices when it comes to coding. One thing that concerns me in my game, is when the player dies and game objects are still looking for it a fraction of a second before the level is reloaded, I get a console full of errors like,
“MissingReferenceException: The object of type ‘GameObject’ has been destroyed but you are still trying to access it.” Is this something that is going to impact performance in the compiled version? Is there a way to clear these, or a way to keep this from happening? I’m going on the assumption that a finished game should never display any errors or warnings in the console.

Yeah, you should be error free.

In that particular instance, it sounds like you’ve got a couple of issues.

The first is that you’re not checking if something is null before you use it. That’s something you should probably do, but don’t just go filling your code with (x != null) everywhere, because…

You seem to be polling (“looking for”) for the player every frame. Typically it’s better to keep local references to things and use those internally, and only update the reference when the thing changes. There are a few ways to do this, one of which is an approach called “events”. Basically, you have some part of your code which is used to communicate to other parts of your code when things change. The thing that does the changing fires an “even”, which anything that cares about that change can “listen” for. So when your player dies it can fire an event saying so just before it gets deleted. All of those things that are throwing null reference errors can listen for that, and stop trying to use the player object. Then, when the new one is created, it can fire an event telling those things that it’s available, and they can start looking at it rather than the old one.

More broadly speaking… remember that you’ve got a whole Mono/.NET runtime at your disposal. Many newbies get caught thinking that everything has to be a MonoBehaviour and that the Unity API is all we’ve got. Thankfully, that’s not the case - you can look up general programming, software design and architecture stuff and most of it applies to Unity. I strongly recommend doing that - I regularly see people who only know “Unity stuff” struggling with things that are pretty well covered elsewhere in the software development world.

3 Likes