should you check to see if a serialized object exists?

Is it redundant to check if a serialized object exists before performing some operation on it? Once attached, there’s really no room for error, correct?

What is a general rule for checking if something exists before using it? For example, should I be checking to see if X object has successfully cached X component on startup before using it, or should I only be checking if something exists if I’m searching for some game object or component that exists outside the object where the script is being called?

There is some objective and subjective part to this topic.
Little speaks against writing code where you check everything that can be null for null before you use it. For example, every method that takes an object as input could check if it’s null, you check everything in Start() and so on. This results in easier to debug code since you practically cannot be surprised by unexpected nulls’. Since you are adding if-statements, technically this is a bit slower, but in practice the performance hit is neglectable so that’s no reason against it for most applications. Especially considering that most null checks probably need to happen in Start() in Unity.

The other extreme end is to just “never” check for null and make sure yourself that your code runs. A lot of things that could be null, are either always null at runtime or never, so this is viable. But it’s only advisable for lazy people who know how to quickly debug code, should a problem occur. It’s probably not the best practice and it’s more prone to unexpected errors.

Your personal style will be somewhere between these two extremes, and that’s fine. There is just one thing to add:
Certain things must always be checked for null, since you cannot make sure that they are not. For certain operations, it is not clear what they return, and it may even be out of your hand. Imagine you are reading from some file - you cant be sure that it’s there. It may not yet have been created, or may have been manually deleted by the user. The same applies if you expect certain hardware to be connected and so on. There are quite a few operations with this behavior, and you may even write your own.

Unless i missed something, the above should sum up the topic of null-checks. Cant really say anything about serialized objects in Unity tho, so i hope someone adds that to answer your main question.

1 Like

If you’re in a situation where a reference should never be null, then it’s appropriate to use an Assert statement. These will throw an error if they are ever null during development, but are stripped out in a production build.

If you’re in a situation where a reference can be null, then you’re looking at explicitly checking for it via an if statement or similar.