Version: 2021.3


interface in UnityEngine




Unity 的序列化器能够序列化大多数(并非全部)数据类型。对于不支持的数据类型,Unity 提供了两个供您手动处理它们的回调函数,以便 Unity 能够序列化和反序列化这些数据类型。

Care needs to be taken whilst within these callbacks, as Unity's serializer runs on a different thread to most of the Unity API. It is advisable to only process fields directly owned by the object, keeping the processing burden as low as possible.

在任何类型的操作期间,都可能需要进行序列化。例如,使用 Instantiate() 克隆对象时,Unity 会对原始对象进行序列化和反序列化,以便查找对原始对象的内部引用,并将它们替换为对克隆对象的引用。在这种情况下,您也可以使用上述回调来更新任何使用了 Unity 无法序列化的类型的内部引用。


This interface is supported on objects that are referenced by SerializeReference. The order of callback execution is not guaranteed between such objects. However it is guaranteed that the main object's OnBeforeSerialize callback would be invoked before those implemented by the referenced objects. And OnAfterDeserialize on the main object would be invoked after it is called on all the referenced objects.

using UnityEngine;
using System;
using System.Collections.Generic;

public class SerializationCallbackScript : MonoBehaviour, ISerializationCallbackReceiver { public List<int> _keys = new List<int> { 3, 4, 5 }; public List<string> _values = new List<string> { "I", "Love", "Unity" };

//Unity doesn't know how to serialize a Dictionary public Dictionary<int, string> _myDictionary = new Dictionary<int, string>();

public void OnBeforeSerialize() { _keys.Clear(); _values.Clear();

foreach (var kvp in _myDictionary) { _keys.Add(kvp.Key); _values.Add(kvp.Value); } }

public void OnAfterDeserialize() { _myDictionary = new Dictionary<int, string>();

for (int i = 0; i != Math.Min(_keys.Count, _values.Count); i++) _myDictionary.Add(_keys[i], _values[i]); }

void OnGUI() { foreach (var kvp in _myDictionary) GUILayout.Label("Key: " + kvp.Key + " value: " + kvp.Value); } }


OnAfterDeserialize实现该方法,以便在 Unity 反序列化您的对象后接收回调。
OnBeforeSerialize实现该方法,以便在 Unity 序列化您的对象前接收回调。