脚本继承ScriptableObject,即可创建可资源化的脚本。
1.创建可资源化的脚本
//可进行资源化处理的脚本需要继承自ScriptableObject
//对应的数据需要可以序列化
//添加CreateAssetMenu可以直接再Create-ScriptableTest中创建
[CreateAssetMenu]
public class ScriptableTest : ScriptableObject
{
[SerializeField]
public List<Info> listInfo;
[System.Serializable]
public class Info
{
public int id;
public string name;
}
}
2.资源化脚本
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
//基于可资源化的脚本创建脚本实例对象
//脚本实例对象后缀为.asset
public class CreateObjectableObject
{
[MenuItem("Assets/Create ScriptableTest Object")]
static void CreateScriptableObject()
{
//创建ScriptableTest实例并赋值
ScriptableTest script = ScriptableObject.CreateInstance<ScriptableTest>();
script.listInfo = new List<ScriptableTest.Info>();
script.listInfo.Add(new ScriptableTest.Info() { id = 100, name = "LLCX" });
//将script保存到本地
AssetDatabase.CreateAsset(script, "Assets/Resources/ScriptableTestObject.asset");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
3.资源读取
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//读取在Resources目录下的资源化的脚本
public class ReadScriptableObject : MonoBehaviour
{
void Start()
{
ScriptableTest scriptableObject = Resources.Load<ScriptableTest>("ScriptableTestObject");
if (scriptableObject.listInfo != null)
{
Debug.LogFormat("scriptableObject id:{0} name:{1}", scriptableObject.listInfo[0].id, scriptableObject.listInfo[0].name);
}
else
{
Debug.Log("Null");
}
}
}
在Edit-ProjectSettings-Editor中AssetSerialization中设置为ForceText则Unity所有的文件包括场景文件等都可以使用文本编辑器打开,就可以直接在里面更改参数了