A scripting attribute that instructs Unity to serialize a field as a reference instead of as a value.
See the serialization manual page for information about serialization and the complete serialization rules.
Without the use of the [SerializeReference]
attribute, Unity serializes each of the fields of an object by value or by reference, depending on the field's type, and according to these serialization rules:
[Serializable]
attribute, it is serialized as a value.In the case of a custom serializable class, this means it serializes only the data belonging to the object assigned to the field, rather than a reference to the object itself. To force Unity to serialize these field types as a reference, use the [SerializeReference]
attribute.
You might want to serialize as a reference rather than a value when:
[SerializeReference]
attribute, your derived classes' additional fields won't be preserved, and your object will instead be serialized as if it was the field's declared type. You can see polymorphism in the SerializeReferencePolymorphismExample
class below.
Optimization
By-value serialization is more efficient than using SerializeReference in terms of storage, memory, and loading and saving time, so you should only use SerializeReference in situations which require it.
The host object and managed references
In the context of SerializeReference, your object which specializes MonoBehaviour, ScriptableObject, ScriptedImporter or other UnityEngine class is called the host object. You can use SerializeReference directly on fields of the host object, or indirectly on fields of custom structures or classes that are serialized within the host object.
The objects assigned to fields with the [SerializeReference]
attribute in the host object are managed references. Each managed reference has a unique ID, which the MonoBehaviour, ScriptableObject or other host object that contains the [SerializeReference]
fields associated with it. By default, Unity generates this ID automatically; to specify an ID, use ManagedReferenceUtility.SetManagedReferenceIdForObject.
When you use SerializeReference, the managed reference objects are only available as shared references within the host object in which they are defined. When a host object is serialized, any managed reference objects are serialized in the "references" section of the serialized data, which is a list located after the serialization of the regular fields. Each managed reference object has an entry in the list, recording its ID, its fully qualified class name, and the value of its fields.
You can see this serialized data for yourself if you're using the default "force text" asset serialization mode. To do this, assign one of the sample scripts below to a GameObject, save the scene, then open the .unity
scene file in a text editor. Each managed reference's data is stored in the .unity
file, under the "references:" section of the serialized MonoBehaviour data.
The managed references are not shared between other UnityEngine.Object instances. If you assign the same custom serializable class object to fields on two different host objects, the serialized references will become separate instances. In addition, if you clone a host object with managed references, this also creates separate copies of all the managed reference objects.
To share referenced values between multiple host objects, use ScriptableObject instead of SerializeReference. ScriptableObject allows you to group a related set of data together as an asset. Because ScriptableObject is derived from UnityEngine.Object, you can share references to them outside of an individual host object. The serialization rules still apply to the fields on the ScriptableObject however, so you may need to use the [SerializeReference]
attribute on fields within your ScriptableObject-derived class.
The SerializeReference attribute is supported on fields whose type is any of the following:
The value assigned to a field with the SerializeReference attribute must, unless it is null, follow these rules:
[SerializeReference]
attribute instead.Notes on the use of SerializeReference with arrays and lists:
List<T>
fields, the SerializeReference attribute applies to the elements of the array or list and not to the array or list object itself.[SerializeReference] public System.Object a = new List<MyCustomClass>(); // UNSUPPORTED
[SerializeReference] public List<MyCustomClass> a = new List<MyCustomClass>(); // VALID
Other Notes:
See Also: SerializedProperty.managedReferenceValue, MonoBehaviour, SerializationUtility, ManagedReferenceUtility.
using System; using UnityEngine;
public class SerializeReferencePolymorphismExample : MonoBehaviour { [Serializable] public class Base { public int m_Data = 1; }
[Serializable] public class Apple : Base { public string m_Description = "Ripe"; }
[Serializable] public class Orange : Base { public bool m_IsRound = true; }
// Use SerializeReference if this field needs to hold both // Apples and Oranges. Otherwise only m_Data from Base object would be serialized [SerializeReference] public Base m_Item = new Apple();
[SerializeReference] public Base m_Item2 = new Orange();
// Use by-value instead of SerializeReference, because // no polymorphism and no other field needs to share this object public Apple m_MyApple = new Apple(); }
using System; using System.Text; using UnityEngine;
public class SerializeReferenceLinkedListExample : MonoBehaviour { // This example shows a linked list structure with a single int per Node. // This would be much more efficiently represented using a List<int>, without any SerializeReference needed. // But it demonstrates an approach that can be extended for trees and other more advanced graphs
[Serializable] public class Node { // This field must use serialize reference so that serialization can store // a reference to another Node object, or null. By-value // can never properly represent this sort of self-referencing structure. [SerializeReference] public Node m_Next = null;
public int m_Data = 1; }
[SerializeReference] public Node m_Front = null;
// Points to the last node in the list. This is an // example of a having more than one field pointing to a single Node // object, which cannot be done with "by-value" serialization [SerializeReference] public Node m_End = null;
SerializeReferenceLinkedListExample() { AddEntry(1); AddEntry(3); AddEntry(9); AddEntry(81); PrintList(); }
private void AddEntry(int data) { if (m_Front == null) { m_Front = new Node() {m_Data = data}; m_End = m_Front; } else { m_End.m_Next = new Node() {m_Data = data}; m_End = m_End.m_Next; } }
private void PrintList() { var sb = new StringBuilder(); sb.Append("Link list contents: "); var position = m_Front; while (position != null) { sb.Append(" Node data " + position.m_Data).AppendLine(); position = position.m_Next; } Debug.Log(sb.ToString()); } }
using System; using System.Collections.Generic; using UnityEngine;
public interface IShape {}
[Serializable] public class Cube : IShape { public Vector3 size; }
[Serializable] public class Thing { public int weight; }
[ExecuteInEditMode] public class BuildingBlocks : MonoBehaviour { [SerializeReference] public List<IShape> inventory;
[SerializeReference] public System.Object bin;
[SerializeReference] public List<System.Object> bins;
void OnEnable() { if (inventory == null) { inventory = new List<IShape>() { new Cube() {size = new Vector3(1.0f, 1.0f, 1.0f)} }; Debug.Log("Created list"); } else Debug.Log("Read list");
if (bins == null) { // This is supported, the 'bins' serialized field is declared as a collection, with each entry as a reference. bins = new List<System.Object>() { new Cube(), new Thing() }; }
if (bin == null) { // !! DO NOT USE !! // Although this is syntactically correct, it is not supported as a valid serialization construct because the 'bin' serialized field is declared as holding a single reference type. bin = new List<System.Object>() { new Cube() }; } } }