最近在参考一个十分优秀的场景跳转管理源码,在Resources目录下发现一个.asset结尾的文件,查了一些资料,发现这也是一种十分不错的数据持久化的方式,今天与大家分享一下。
先来创建一个需要存储数据的类
注:该类一定要是可序列化的。一定要继承与ScriptableObject类。
using System;
using UnityEngine;
[Serializable]
public class NewBehaviourScript : ScriptableObject {
public int testSpeed = 100;
public GameObject testGo;
}
接下来实现生成自定义资源的脚本
using System.IO;
using UnityEditor;
using UnityEngine;
public class CreateAssetBegin : Editor {
[MenuItem("Tools/Create")]
public static void Creat()
{
ScriptableObject test = ScriptableObject.CreateInstance<NewBehaviourScript>();
string path = Application.dataPath + "/XXX";
if (!xx)
{
Debug.LogWarning("无法找到");
return;
}
// 如果项目总不包含该路径,创建一个
if (!Directory.Exists(path))
{
Debug.Log("创建路径开始");
Directory.CreateDirectory(path);
Debug.Log("创建成功");
}
//将类名 Bullet 转换为字符串
//拼接保存自定义资源(.asset) 路径
path = string.Format("Assets/XXX/{0}.asset", (typeof(NewBehaviourScript).ToString()));
Debug.Log(test+" "+path);
// 生成自定义资源到指定路径
AssetDatabase.CreateAsset(test,path);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
注:在生成资源时,路径一定要是Asset目录下的文件加,不能实用Application.dataPath来设置路径,否则会报错
获取自定义资源只需要一句代码
NewBehaviourScript xx= AssetDatabase.LoadAssetAtPath<NewBehaviourScript>("Assets/XXX/NewBehaviourScript.asset");
只要把路径写对,读取就没有问题。
自定义资源几乎可以保存Unity中所有的类型,要比Json Xml强不少哦