在序列化和反序列化时接收回调的接口。
Unity 的序列化器能够序列化大多数(并非全部)数据类型。对于不支持的数据类型,Unity 提供了两个供您手动处理它们的回调函数,以便 Unity 能够序列化和反序列化这些数据类型。
使用这两个回调时需要注意,Unity 的序列化器运行在与大多数 Unity API 不同的线程上,因此,建议只处理数据类型操作,以尽可能减轻处理负担。
在任何类型的操作期间,都可能需要进行序列化。例如,使用 Instantiate() 克隆对象时,Unity 会对原始对象进行序列化和反序列化,以便查找对原始对象的内部引用,并将它们替换为对克隆对象的引用。在这种情况下,您也可以使用上述回调来更新任何使用了 Unity 无法序列化的类型的内部引用。
目前,该回调接口仅适用于类,不能用于结构。
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 序列化您的对象前接收回调。 |
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.