Unity将一个类序列化并以.asset类型存储在Resources文件夹下

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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⽂件夹下产⽣⼀个存储的⽂件,(没有反应的话重新打开此场景)如下:。

相关文档
最新文档