问题
最近有两个朋友都问了我这个问题,在Editor脚本中,获取target修改里面的数据,没法保存,SetDirty()根本无效,只能通过改改别的地方能保存时候,保存一下。大概代码如下:
//--运行时脚本,里面有AAA属性
using UnityEngine;
public class ShadowMapTest : MonoBehaviour
{
public int AAA;
}
//--编辑器脚本
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(ShadowMapTest))]
public class ShadowMapTestEditor : Editor
{
ShadowMapTest ShadowMapTest;
// Start is called before the first frame update
public override void OnInspectorGUI()
{
ShadowMapTest = target as ShadowMapTest;
if (GUILayout.Button("555"))
{
ShadowMapTest.AAA = 555;
}
EditorGUILayout.LabelField("显示数据:" + ShadowMapTest.AAA);
serializedObject.ApplyModifiedProperties();
}
}
通过如上代码我们做如下实验:
我们初始化一下场景:
做如下操作:
好~问题大概就是这样,上面的问题数据明明发生了改变,却无法触发保存。
解决方案1-使用SerializedProperty
我们使用如下代码
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(ShadowMapTest))]
public class ShadowMapTestEditor : Editor
{
ShadowMapTest ShadowMapTest;
SerializedProperty AAA;
// Start is called before the first frame update
public override void OnInspectorGUI()
{
ShadowMapTest = target as ShadowMapTest;
AAA = serializedObject.FindProperty("AAA");
if (GUILayout.Button("555"))
{
AAA.intValue = 555;
}
EditorGUILayout.LabelField("显示数据:" + ShadowMapTest.AAA);
serializedObject.ApplyModifiedProperties();
}
}
是可以触发变更的,因为SerializedProperty 的setter会自动触发change。如果属性是Arry我们可以通过如下方法进行设置。
public void InsertArrayElementAtIndex(int index);//插入元素
public void DeleteArrayElementAtIndex(int index);//删除元素
public bool MoveArrayElement(int srcIndex, int dstIndex);//调整元素位置
public IEnumerator GetEnumerator();//获取迭代器,可以遍历数据
解决方案2-Undo.RecordObject
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(ShadowMapTest))]
public class ShadowMapTestEditor : Editor
{
ShadowMapTest ShadowMapTest;
// Start is called before the first frame update
public override void OnInspectorGUI()
{
ShadowMapTest = target as ShadowMapTest;
if (GUILayout.Button("555"))
{
//--再此记录
Undo.RecordObject(ShadowMapTest, "TTT");
ShadowMapTest.AAA = 555;
}
EditorGUILayout.LabelField("显示数据:" + ShadowMapTest.AAA);
serializedObject.ApplyModifiedProperties();
}
}
使用这个方法后也可以记录修改的信息。而且我们不需要使用SerializedProperty查来查去的。
复杂数据结构测试
上面我们都是简单的数据结构,如果我们的数据结构边的复杂一点,如下:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShadowMapTest : MonoBehaviour
{
public int AAA;
public List<int> A = new List<int>();
public TestData TestData;
}
[Serializable]
public class TestData
{
public List<int> A=new List<int>();
}
经测试,我们使用上述两个方法修改任何一个属性都可以触发保存。