Unity - 序列化 ScriptableObject、SerializedProperty 编辑器运用
2015-12-19 16:49
453 查看
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(); } }
相关文章推荐
- Unity3D手游开发日记(2) - 技能系统架构设计
- win8.1下unity串口投币器(纸钞识别器)开发
- Unity3D手游开发日记(1) - 移动平台实时阴影方案
- Unity3D-C#扩展方法
- Unity中的Serializable
- Unity3D-MONO脚本自带函数执行顺序
- Unity3D-PlayerPrefs本地数据保存读取
- Unity3D性能优化总结(转纳金网)
- Unity Shader入门介绍
- Unity5.3Json测试学习
- 使用unity3d 接入anySDK的总结1
- Unity加载和内存管理机制(二)
- Unity加载和内存管理机制(一)
- Drawcall总结-Unity5.X
- 宣雨松版《Unity3D游戏开发》最后章节实战《突出重围》逻辑整理
- unity3d 依据指定的Assets下的目录路径 返回这个路径下的全部文件名称
- “400 Bad Request”解决办法及Unity下载文件保存到本地
- 小米游戏中心sdk接入unity
- iOS与Unity3d的交互实现
- Unity插件之NGUI学习(5)—— 创建Label图文混排及文字点击