|
1 | | -# GenericSerializeReference |
2 | | -Make a field with generic type serializable by mark with [GenericSerializeReference] attribute. |
| 1 | +```c# |
| 2 | +public interface IMyInterface<T> {} |
| 3 | +public class MyIntObject : IMyInterface<int> {} |
| 4 | + |
| 5 | +public class MyMonoBehavior : MonoBehaviour |
| 6 | +{ |
| 7 | + [GenericSerializeReference] |
| 8 | + public IMyInterface<int> Value { get; set; } |
| 9 | +} |
| 10 | +``` |
| 11 | + |
| 12 | + |
| 13 | +# Limitations |
| 14 | +- Only types from referenced assemblies could be show up in inspector. |
| 15 | +- Not support `struct` type |
| 16 | + |
| 17 | +# Costs |
| 18 | +- Extra time to generate IL instructions while building assembly |
| 19 | +- Extra memory space to store a generated field for each property. |
| 20 | + |
| 21 | +# How it works |
| 22 | +```c# |
| 23 | +public class MyMonoBehavior : MonoBehaviour |
| 24 | +{ |
| 25 | + // [GenericSerializeReference] |
| 26 | + // public IMyInterface<int> Value { get; set; } |
| 27 | +
|
| 28 | + // 1. gather derived types of property (`IMyInterface<>`) |
| 29 | + // then generate a concrete version of those types and make them all implement `IBase` interface |
| 30 | + private static class <Value>__generic_serialize_reference |
| 31 | + { |
| 32 | + public interface IBase {} |
| 33 | + public class MyIntObject : global::MyIntObject, IBase {} |
| 34 | + } |
| 35 | + |
| 36 | + // 2. create a field named _Value with `IBase` type |
| 37 | + // which should be able to serialized by `SerializeReference` attribute |
| 38 | + [SerializeReference, GenericSerializeReferenceGeneratedField] |
| 39 | + private <Value>__generic_serialize_reference.IBase _Value; |
| 40 | + |
| 41 | + // 3. inject code into property's getter and setter |
| 42 | + // make sure property get value from serialized field first |
| 43 | + // and set serialized field into null to avoid get from it next time. |
| 44 | + [GenericSerializeReference] |
| 45 | + public IMyInterface<int> Value |
| 46 | + { |
| 47 | + get |
| 48 | + { |
| 49 | + return (IMyInterface<int>) _Value ?? <Value>k__backingField; |
| 50 | + } |
| 51 | + set |
| 52 | + { |
| 53 | + <Value>k__backingField = value; |
| 54 | + _Value = null; |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
0 commit comments