版权声明:个人原创,转载请注明出处 https://blog.csdn.net/dengshunhao/article/details/82287622
官方API地址: https://docs.unity3d.com/ScriptReference/Serializable.html
对于Serializable,博主一直是一知半解的,虽然大致知道是什么意思,但是就是不知道为何要用这个,因此翻译下官方文档,希望能理解的更加透彻
描述:
The Serializable attribute lets you embed a class with sub properties in the inspector.
You can use this to display variables in the inspector similar to how a Vector3 shows up in the inspector. The name and a triangle to expand its properties. To do this you need create a class that derives from System.Object and give it the Serializable attribute. In JavaScript the Serializable attribute is implicit and not necessary.
Serializable属性允许您在inspector中嵌入带有子属性的类。
您可以使用它来显示检查器中的变量,类似于Vector3在检查器中显示的方式。它的名称和一个三角形来扩展它的
属性。要做到这一点,您需要创建一个源自系统的类。对象并赋予它可串行化属性。在JavaScript中,
Serializable属性是隐式的,而不是必需的。
看到这里还是懵的,那就实例操作一下看有什么效果:
序列化的类:
using UnityEngine;
[System.Serializable]
public class Test : System.Object
{
public int p = 5;
public Color c = Color.white;
}
显示类:
using UnityEngine;
using System.Collections;
public class Show : MonoBehaviour
{
public Test[] propertys;
string strSex;
public void Start()
{
propertys = new Test[4];
for (int i = 0; i < propertys.Length; i++)
{
propertys[i] = new Test();
propertys[i].p = i;
propertys[i].c = new Color((float)i/10, (float)i / 10, (float)i / 10);
}
}
}
效果显示:
如果不序列化,则不会显示:
感觉挺不错的,也就是说另一个类使用其他类,其他类序列化,则在类中可看到其他类中的属性值