it will obviously not work because I didn’t create an instance and the class is not static.
But when I write [System.Serializable] above the class, this will suddenly work. Why? Does serialization mean in this context that it created an instance?
In the Unity editor, when you use the inspector to examine a script, it displays all of that script’s serializable fields in the window, so that you can view and edit their values and save them as the “starting” values for that particular instance.
When you do that, if any of the serializable objects are null, Unity automatically creates an instance for you and saves that. (Except for some special types that the inspector treats as references rather than values, such as MonoBehaviours.) They have basically written their serializer to not allow nulls.
This can be a source of some very confusing bugs if you don’t know its happening. For instance, if you write code that intentionally sets a value to null during runtime, it will work–unless you select that particular object in the editor, which will invoke the serializer and replace the null value. (Tip: if you want to allow a field on your MonoBehaviour to be null, make sure that field is NOT serialized.)
Thanks for the reply! I already knew about serializing single values to let them be visible in the editor but the weird thing about this is that my class doesn’t even derive from monobehaviour, yet I still can use the System.Serializable attribute.
And where is the instance stored? Do I just access it with “exampleScript.randomVariable;” kind of like I would do it with a static variable?
I’m having actually a very similar issue where I’m using the ISerializationCallbackReceiver-Interface. It is confusing me so much haha. My solution is to just not click on the asset when I’m in play mode. Unities serialization is so weird especially for a beginner.