SerializeReference Attribute?

The field attribute is for serializing reference types (c# class, not structs) by reference as opposed to by value (as is the default behaviour).

This allows:

  • Expressing graphs without having to resort to ScritableObjects for each node in the graph.
  • Polymorphic data, ex: List;
  • Have null fields: Standard deserialization behaviour for fields that are null is to set them to a default value of the type.

contrived usage example:

interface INode{  }

[Serializable]
class RootNode : INode
{
   [SerializeReference] public INode left;
   [SerializeReference] public INode right;
}

[Serializable]
class SubNode : RootNode
{
   [SerializeReference] INode parent;
}

[Serializable]
class LeafNode : INode
{
   [SerializeReference] public INode parent;
}


class SomeThing : ScriptableObject
{
    [SerializeReference]
    public List<RootNode>  m_Trees;
}
44 Likes