Delegates are one of the nicer features of C#. They’re essentially high-level and type-safe references to methods. But, like pretty much every fancy C# feature, delegate values are not serializable by default. If you hold a reference to a delegate, it will be lost during code hot-reload. I will show you a way to serialize them and explain how they work.
Note: This solution is inspired by the uFAction tool in Unity, which I am not affiliated with. Go check it out here.
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.
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.
Serializing is the process in which a binary object (i.e. a class or a struct) is converted to a binary stream. Deserializing is the process in which an object is created from a binary stream. In layman’s terms, this is just a fancy schmancy way to say that a class or a struct is Saved and then Loaded from memory (be it virtual memory or an actual file on disk).
Warning: This does not necessarily mean that serialization is only used when you’re trying to save or load the game to or from a disk! If you’re not planning to have that in your game, it doesn’t make this article any less important. The fact is, Unity serializes and deserializes data all the time, so you have already used serialization whether you’ve realized it or not. And, if you don’t know what you’re doing, serialization can fail when you need to use custom classes (or even many default .NET classes), leading to very strange errors which seemingly come out of nowhere.