强制 Unity 对私有字段进行序列化。
当 Unity 对脚本进行序列化时,仅对公共字段进行序列化。
如果还需要 Unity 对私有字段进行序列化,
可以将 SerializeField 属性添加到这些字段。
Unity 将对所有脚本组件进行序列化,重新加载新程序集,
并从序列化的版本重新创建脚本组件。此
序列化是通过 Unity 内部序列化系统完成的;而不是通过
.NET 的序列化功能来完成。
序列化系统可执行以下操作:
- 可序列化(可序列化类型的)公共非静态字段
- 可序列化标记有 SerializeField 属性的非公共非静态字段。
- 不能序列化静态字段。
- 不能序列化属性。
可序列化的类型
Unity 可序列化以下类型的字段:
- 继承 UnityEngine.Object 的所有类,例如 GameObject、Component、MonoBehaviour、Texture2D、AnimationClip。
- 所有基本数据类型,例如 int、string、float、bool。
- 某些内置类型,例如 Vector2、Vector3、Vector4、Quaternion、Matrix4x4、Color、Rect、LayerMask。
- 可序列化类型数组
- 可序列化类型列表
- 枚举
- 结构
有关序列化的更多信息,请参阅脚本序列化。
注意:如果在一个列表(或数组)中将一个元素放置两次,当此
列表被序列化时,将获得该元素的两个副本,而不是获得两次新列表中的一个副本。
注意:如果要序列化自定义 Struct 字段,则必须为该 Struct 给定 [System.Serializable] 属性。
提示:Unity 不会序列化 Dictionary,但您可以为键存储一个 List<>
和为值存储一个 List<>,然后在
Awake() 上将它们组合在非序列化字典中。这不能解决您需要修改字典
并将其“保存”回时出现的问题,但在许多其他情况下,这是一个方便的技巧。
using UnityEngine;
public class SomePerson : MonoBehaviour { //This field gets serialized because it is public. public string firstName = "John";
//This field does not get serialized because it is private. private int age = 40;
//This field gets serialized even though it is private //because it has the SerializeField attribute applied. [SerializeField] private bool hasHealthPotion = true;
void Start() { if (hasHealthPotion) Debug.Log("Person's first name: " + firstName + " Person's age: " + age); } }
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.