美文网首页
unity3d 序列化Serializable

unity3d 序列化Serializable

作者: UnityAsk | 来源:发表于2017-02-20 20:39 被阅读1198次

from:
http://www.jianshu.com/p/af878d967c84

在脚本使用只需要序列化的类名前面加上 [Serializable]即可,加上System命名空间。

[Serializable]
class Animal
{
   public string name;
}

class MyScript : MonoBehaviour
{
      public Animal[] animals;
}

这个写法可以把类中公共变量做序列化,私有变量需要序列化需要加上[SerializeField],公共变量不想被序列化加上 [NonSerializable]就可以了。当然静态(static),常量(const),只读(readonly)的变量,抽象类这些是不能被序列化的。

二进制序列化简单例子

数据类:

[Serializable]
public class MyTest
{
    public int age;
    public string name;

    public override string ToString()
    {
        return String.Format("Age: {0}, Name: {1}", age, name);
    }
}

操作:

   public void OnGUI()
   {
    if (GUILayout.Button("Save"))
    {
        var file = File.Open(Application.dataPath + "/myTest.dat", FileMode.OpenOrCreate);
        var bf = new BinaryFormatter();
        var myTest = new MyTest {age = 2, name = "ben"};
        bf.Serialize(file, myTest);
        file.Close();
    }
    if (GUILayout.Button("Load"))
    {
        if (File.Exists(Application.dataPath + "/myTest.dat"))
        {
            var file = File.Open(Application.dataPath + "/myTest.dat", FileMode.Open);
            var bf = new BinaryFormatter();
            var myTest = (MyTest) bf.Deserialize(file);
            file.Close();
            Debug.Log(myTest.ToString());
        }
    }
}

相关文章

网友评论

      本文标题:unity3d 序列化Serializable

      本文链接:https://www.haomeiwen.com/subject/gxnewttx.html