【Unity】记录一下:自定义组件的InspectorGUI面板,修改数据不保存问题
使用target修改之后需要使用EditorUtility.SetDirty设置为脏,但是要注意的是应该设置target所指代的组件,而非是对.gameObject 设置为脏,这是没有用的。
[CustomEditor(typeof(MerryGoRound))]
public class MerryGoRoundEditor : Editor
{
public override void OnInspectorGUI()
{
var obj = target as MerryGoRound;
EditorGUI.BeginChangeCheck();
obj.rudis = EditorGUILayout.FloatField("半径", obj.rudis);
obj.viry = EditorGUILayout.FloatField("幅度", obj.viry);
if(EditorGUI.EndChangeCheck() && !EditorUtility.IsDirty(target))
EditorUtility.SetDirty(target);
}
}
还有一种办法是,根据serializedObject修改对应的变量值,但是这个办法比较麻烦。推荐用第一种的,记住设置target为脏而不是对于的gameobject。
[CustomEditor(typeof(MerryGoRound))]
public class MerryGoRoundEditor : Editor
{
public override void OnInspectorGUI()
{
var obj = target as MerryGoRound;
var prop = serializedObject.FindProperty("rudis");
prop.floatValue = EditorGUILayout.FloatField("半径", prop.floatValue);
if(serializedObject.hasModifiedProperties)
serializedObject.ApplyModifiedProperties();
}
}