问题
使用版本unity2017.4.4f1。
使用脚本批量创建自定义Asset,并给与赋值,发现赋值数据并没有被保存下来。
而手动赋值后,按下ctrl+s才会保存数据,知道了原因。
解决办法
自动赋值不会使Asset文件发生被改写的状态,需要加上
EditorUtility.SetDirty(ScriptableObject target);
告诉文件引擎这个文件发生了改变,
然后再保存:
AssetDatabase.SaveAssets();
代码片段如下
//...此为代码片段...
[MenuItem("Tools/保存Asset文件")]
static void SaveAssets()
{
if (heroList.Count < 1)
{
return;
}
if (!Directory.Exists(heroAssetPath))
{
Directory.CreateDirectory(heroAssetPath);
}
foreach (HeroPropertyBase h in heroList)
{
ScriptableObject sobj = ScriptableObject.CreateInstance<HeroAsset>();
string path = heroAssetPath + "/" + h.ID + ".asset";
if (!File.Exists(path))
{
AssetDatabase.CreateAsset(sobj, path);
Debug.Log("创建HeroAsset:" + path);
}
HeroAsset ha = AssetDatabase.LoadAssetAtPath<HeroAsset>(path);
ha.heroPropertyBase = h;
//标记目标已被改变数值
EditorUtility.SetDirty(ha);
//储存
AssetDatabase.SaveAssets();
}
Debug.Log("HeroAsset创建完成!");
}