Unity - 序列化 ScriptableObject、SerializedProperty 编辑器运用
结合编辑器类使用序列化, 将数据显示在 Inspector 面板,并且执行序列化保存数据。
如图
上图为将自定义类 Npc
使用编辑器类显示在 Inspector面板
// Npc 类如下
[System.Serializable]
public class Npc
{
public int npcID;
public int nameID;
public float speed;
public float life;
}
// 新建 NpcClass.cs 脚本
public class NpcClass : MonoBehaviour {
public Npc npc;
void Start () {
}
void Update () {
}
}
// 新建 NpcClassEditor.cs 放在 Editor 文件夹下,代码如下
using UnityEngine;
using System.Collections;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(NpcClass))]
public class NpcClassEditor : Editor {
private SerializedProperty npc;
private GUIContent debugBtn;
void OnEnable()
{
// 使用 serializedObject.FindProperty 方法
// 获取 NpcClass 中定义的 public Npc npc; 变量
npc = serializedObject.FindProperty("npc");
debugBtn = new GUIContent("Debug");
debugBtn.tooltip = "Debug values about the npc";
}
public override void OnInspectorGUI()
{
serializedObject.Update();
DrawNpc();
if (GUI.changed)
{
EditorUtility.SetDirty(target);
}
serializedObject.ApplyModifiedProperties();
}
// 绘制 Npc 类属性
private void DrawNpc()
{
EditorGUILayout.BeginVertical("box");
GUILayout.Space(5);
// 获取 npc 类中的 npcID 属性
SerializedProperty npcID = npc.FindPropertyRelative("npcID");
// 将 npcID 属性绘制在 Inspector 面板
EditorGUILayout.PropertyField(npcID, new GUIContent("NpcID"));
GUILayout.Space(5);
SerializedProperty nameID = npc.FindPropertyRelative("nameID");
EditorGUILayout.PropertyField(nameID, new GUIContent("NameID"));
GUILayout.Space(5);
SerializedProperty speed = npc.FindPropertyRelative("speed");
EditorGUILayout.PropertyField(speed, new GUIContent("Speed"));
GUILayout.Space(5);
SerializedProperty life = npc.FindPropertyRelative("life");
EditorGUILayout.PropertyField(life, new GUIContent("Life"));
GUILayout.Space(5);
Rect btPosition = GUILayoutUtility.GetRect(debugBtn, GUI.skin.button);
const float addButonWidth = 150f;
btPosition.x = btPosition.x + (btPosition.width - addButonWidth) / 2;
btPosition.width = addButonWidth;
if (GUI.Button(btPosition, debugBtn))
{
Debug.Log("npcID :" + npcID.intValue);
Debug.Log("nameID :" + nameID.intValue);
Debug.Log("speed :" + speed.floatValue);
Debug.Log("life :" + life.floatValue);
}
EditorGUILayout.EndVertical();
}
}