Unity 將一個類序列化並以 ".asset" 類型存儲在 Resources 文件夾下


概念:

序列化 (Serialization)將對象的狀態信息轉換為可以存儲或傳輸的形式的過程。在序列化期間,對象將其當前狀態寫入到臨時或持久性存儲區。以后,可以通過從存儲區中讀取或反序列化對象的狀態,重新創建該對象。

實現例子:

寫一個MyClass類,提供了可被序列化的屬性,不用其余操作,如下:

using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
public class MyClass : ScriptableObject
{

    public void SetBoolenTest(bool value)
    {
        boolenTest = value;
        DirtyEditor();
    }

    public void SetIntTest(int value)
    {
        intTest = value;
        DirtyEditor();
    }

    public void SetStrTest(string value)
    {
        strTest = value;
        DirtyEditor();
    }

    public void SetStrIndex(int index)
    {
        strIndex = index;
        SetStrTest(strList[index]);
        DirtyEditor();
    }

    private void DirtyEditor()
    {
        EditorUtility.SetDirty(Instance);
    }

    public bool BoolenTest
    {
        get
        {
            return Instance.boolenTest;
        }
    }
    public int IntTest
    {
        get
        {
            return Instance.intTest;
        }
    }
    public string StrTest
    {
        get
        {
            return Instance.strTest;
        }
    }
    public int StrIndex
    {
        get
        {
            return strIndex;
        }
    }

    [SerializeField]
    private bool boolenTest = true;
    [SerializeField]
    private int intTest = 1;
    [SerializeField]
    private string strTest = "hello world";
    [SerializeField]
    private int strIndex = 0;

    public string[] strList = new string[] { "str_1", "str_2", "str_3" };

    private static MyClass _instance;
    public static MyClass Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = Resources.Load("MyClass") as MyClass;
            }
            if (_instance == null)
            {
                _instance = CreateInstance<MyClass>();
                AssetDatabase.CreateAsset(_instance, "Assets/Resources/MyClass.asset");
            }
            return _instance;
        }
    }
}

寫一個測試類,不用其余操作,如下:

using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class ToolsTest : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        
    }

    [MenuItem("EditorTools/Test")]
    public static void Test()
    {
        var myClass = MyClass.Instance;
        myClass.SetIntTest(666);
        myClass.SetBoolenTest(false);
        myClass.SetStrTest("hello,I am black");


    }
}

Unity菜單欄會出現 EditorTools —Test 按鈕,此時新建一個Resources文件夾,然后點擊按鈕(沒有Resources文件夾點擊按鈕沒反應),就會在Resources文件夾下產生一個存儲的文件,(沒有反應的話重新打開此場景)如下:

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM