ScriptableObject类定制可序列化数据
这个类很有用,它可以打包数据对象,并且这个数据对象是序列化的,用来存储数据非常方便,比json xml等更方便,容易存取,这里用它做一个简单的使用案例。
工具类ScriptableObjectUtility
打包工具类,需放到Editor文件夹内
using UnityEngine;
using UnityEditor;
using System.IO;
public static class ScriptableObjectUtility
{
// This makes it easy to create, name and place unique new ScriptableObject asset files.
public static void CreateAsset<T> () where T : ScriptableObject
{
T asset = ScriptableObject.CreateInstance<T> ();
string path = AssetDatabase.GetAssetPath (Selection.activeObject);
if (path == "")
{
path = "Assets";
}
else if (Path.GetExtension (path) != "")
{
path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), "");
}
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/New " + typeof(T).ToString() + ".asset");
AssetDatabase.CreateAsset (asset, assetPathAndName);
AssetDatabase.SaveAssets ();
AssetDatabase.Refresh();
EditorUtility.FocusProjectWindow ();
Selection.activeObject = asset;
}
}
创建对应的数据类MyData
using UnityEngine;
using System.Collections.Generic;
public class YourClass : ScriptableObject {
public List<MyData> dialogue=new List<MyData>();
}
这个类中存储你需要序列化存储的打包数据
using UnityEngine;
using System.Collections;
[System.Serializable]
public class MyData{
public enum sexual {male ,female};
public string Name;
public int age;
public string dialogue;
public AudioClip m_audio;
}
打包按钮
加一句废话,要放到Editor文件夹里面
using UnityEngine;
using UnityEditor;
public class YourClassAsset
{
[MenuItem("Assets/Create/YourClass")]
public static void CreateAsset ()
{
ScriptableObjectUtility.CreateAsset<YourClass> ();
}
}
生成数据文件
点击YouClass按钮就会生产如下文件
这时我们可以看到,这个文件可以进行赋值操作的如下图
读取数据
首先创建代码如下,当然New YourClass文件要放到Resources文件夹下
using UnityEngine;
using System.Collections;
public class LoadClass : MonoBehaviour {
void Start () {
YourClass dia= Resources.Load ("New YourClass") as YourClass;
for (int i = 0; i < dia.dialogue.Count; i++) {
MyData data = dia.dialogue [i];
Debug.Log (data.name+"--- "+data.age+" :"+data.dialogue);
}
}
}
将这个脚本放到场景物体上运行Unity
本文工程:http://download.csdn.net/detail/warrenmondeville/9694660
本文连接:http://blog.csdn.net/warrenmondeville/article/details/53329038