Unity中的序列化Scriptable

遊戲中保存數據的途徑有三種:

  • PlayerPrefs
  • csv, xml, json等配置文件
  • Scriptable序列化

  • PlayerPrefs與配置文件的缺點

  • PlayerPrefs只能在運行時保存讀取一些臨時數據
  • 配置文件,需要加載進來後解析爲具體的數據對象,然後學要在代碼中獲取對應的數據對象

  • Scriptable優點:

  • 可以直接將對象序列化到本地,以asset的方式存儲
  • 可以在Inspector窗口預覽編輯asset
  • 通過拖拽直接被Monobehaviour引用,不用手動加載
  • 自動解析爲對象
  • 但如果將asset打包成assetbundle,則需要在代碼中手動加載,不可以直接通過拖拽來引用了

  • 定義可序列化類

    public class TestScriptable : ScriptableObject
    {
        public int id;
    
        public List<MyClass> lst;
    }
    
    // Scriptable引用到的類,要聲明爲Serializable
    [Serializable]
    public class MyClass
    {
    }

    生成本地Scriptable asset

    [MenuItem("Assets/Create/CreateSO")]
    public static void CreateSO()
    {
        TestScriptable s = ScriptableObject.CreateInstance<TestScriptable>();
        AssetDatabase.CreateAsset(s, "Assets/Resources/test.asset");
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();  
    }

    使用AssetDatabase加載

    TestScriptable ts = AssetDatabase.LoadAssetAtPath("Assets/Resources/test.asset", typeof(ScriptableObject)) as TestScriptable;
            Debug.Log(ts.id);

    使用Resource加載

    TestScriptable ts = Resources.Load("test") as TestScriptable;
    Debug.Log(ts.id);

    使用www加載

    IEnumerator Start ()   
    {                
        WWW www = new WWW("file://" + Application.dataPath + "/test.assetbundle");                
        yield return www;    
    
        TestScriptable ts = www.assetBundle.mainAsset as TestScriptable;   
    
        Debug.Log(ts.id);
    }  

    https://docs.unity3d.com/560/Documentation/Manual/class-ScriptableObject.html

    發佈了58 篇原創文章 · 獲贊 5 · 訪問量 11萬+
    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章