class in UnityEngine
/
Implemented in:UnityEngine.CoreModule
Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.
CloseFor some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.
CloseA 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() }; } } }
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.