I have a situation where a public variable ( array ), called Audio_Prefabs, in a monobehaviour script on a component is null. I havent had this issue before this project and have at least 150 other components that works fine.
At some point in code I check for length:
if(m_audioPrefabs.Length == 0) ← this throws an exception saying m_audioPrefabs is null.
I can not find any information that clarifies if a public variable ( that is visible in the editor ) can be expected, at any time, to be null if not explicitly instantiated.
This is an edge case, possibly what you are seeing: if you create a prefab or save a scene, then add a new array variable, its value will be null rather than an array of length of zero.
One way to fix is to just resave the prefab/scene, at least by changing one thing and changing it back.
Yes, non-primitive variables can be null under some circumstances. Unity’s serializer doesn’t support null, so whenever an object has been serialized and then deserialized again, all variables are non-null. However, if an object is freshly created and hasn’t been deserialized, all variables have their default C# values, which can be null.
You can either initialize those variables in the constructor / through initializers or always check if they’re null. The first is more convenient but will create duplicate objects in most cases (the one created by the constructor/initializer is later overwritten by the deserializer).