Starting from Unity 4.5, any class can be made to inherit from
ISerializationCallbackReceiver. This allows us to write methods that can be used to control seialization and deserialization, and it demands from the class to implement two public methods:
OnAfterDeserialize(). These methods are automatically called when that class inherits from
UnityEngine.Object or is marked with the
The idea behind this concept is both simple and powerful, but there are certain things you need to have in mind. Not only I will show you how to use this interface, I will also provide some information on things you should avoid or on things that won’t work as expected.
ScriptableObjects become (unfortunately) necessary when you start developing editor tools. That, and every other class that inherits from
UnityEngine.Object, has the unique ability to maintain proper references after deserialization. Every other class creates a copy per reference (as if it were a struct) after deserialization, which can be very troublesome.
One of the least pleasant aspects of ScriptableObject is that you cannot control their instantiation. Using their constructor to create them does not work as expected. The only proper way to create a ScriptableObject from scratch is to call the
ScriptableObject.CreateInstance<DerivedType>() static method, where
DerivedType is a type which derives from
ScriptableObject. Unfortunately, This method does not take any parameters. I will show you an easy way to help control their instantiation, so that the users of your ScriptableObject classes will be less prone to use them incorrectly.
C# Properties are one of the nicer features of C#, but there are things to keep in mind when using them in Unity. The framework doesn’t seem to like them too much. I will show you what the Unity-specific problems on using properties are and how to easily address them.