unity-序列化对象-ScriptableObject

可以将 继承于 ScriptableObject 的类序列化成 .asset 资源, 可用于配置, 里面引用的资源在打 assetbundle 时可以形成引用.


使用流程

  1. 自定义一个类 MyScriptableObject 继承 ScriptableObject

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    // 定义创建菜单, 在 create -> ScriptableObject -> MyScriptableObject 可以创建该类的序列化资源,
    // 也可以参考 OtherScriptableObject.cs 程序创建资源
    [CreateAssetMenu(menuName = "ScriptableObject/MyScriptableObject")]
    public class MyScriptableObject : ScriptableObject {

    public string myname = "yangx";
    public int age = 11;
    [Range(0, 20)]
    public float raduis = 12.3f;

    public Content content = new Content();

    public List<Texture> texList = new List<Texture>();

    }

    // 里面要序列化自定属性要加上这个 属性标记
    [System.Serializable]
    public class Content {
    public string en;
    public string cn;
    public string jp;
    }
  2. 创建 .asset 资源. 两种方式

    1. 右键创建 create -> ScriptableObject -> MyScriptableObject

    2. 程序创建

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      public void CreateScriptableObject() {
      MyScriptableObject ins = ScriptableObject.CreateInstance<MyScriptableObject>();
      ins.myname = "hello";
      ins.age = 111;
      ins.raduis = 4.2f;
      string path = "Assets/Z_Other/ScriptableObject/MySO2.asset";

      string texpath1 = "Assets/Common/tex/build_sh_jb.png";
      string texpath2 = "Assets/Common/tex/Plasma_1.png";
      Texture tex1 = AssetDatabase.LoadAssetAtPath<Texture>(texpath1);
      Texture tex2 = AssetDatabase.LoadAssetAtPath<Texture>(texpath2);

      ins.texList.Add(tex1);
      ins.texList.Add(tex2);

      AssetDatabase.CreateAsset(ins, path);
      Debug.LogFormat("--- CreateAsset success, path:{0}", path);
      }
    3. 加载资源, 也就是反序列化

      1
      2
      3
      4
      5
      public void LoadScriptableObject() {
      string path = "Assets/Z_Other/ScriptableObject/MySO2.asset";
      MyScriptableObject ins = AssetDatabase.LoadAssetAtPath<MyScriptableObject>(path);
      Debug.LogFormat("--- LoadAsset success, {0}, {1}, {2}, {3}", ins.myname, ins.age, ins.raduis, ins.texList.Count);
      }

assetbundle 打包测试

MyAsset01.asset (存放于 config 文件夹) 中引用了两张图片 (来自于 config2 文件夹)

当把 config2 文件夹也打成一个 ab 时, config 的 ab 会引用 config2 的 ab, 所以 config 的 ab 很小

当把不打 config2 的 ab 时, config 的 ab 会把引用的图片直接打进去, 所以比较大.

这样可以证明, MyAsset01.asset 和正常的资源一样, 打包是可以形成引用关系. 不像脚本里引用资源是不会打进ab包内, 也不会形成引用