标签:images 自定义 function system cal 装备 can 赋值 field
UnityEditor研究学习之自定义Editor
今天我们来研究下Unity3d中自定义Editor,这个会让物体的脚本在Inspector视窗中,产生不同的视觉效果。
什么意思,举个例子,比如游戏中我有个角色Player,他有攻击力,护甲,装备等属性。
所以我定义一个脚本:MyPlayer.cs:
using UnityEngine; using System.Collections; public class MyPlayer : MonoBehaviour { public int armor = 100; public int attack = 100; public GameObject equipment; void Start() { } void Update() { } }
这边我定义了三个变量,分别是护甲、攻击力还有GameObject类型的装备。
将这个脚本赋值给GameObject,可以看到Inspector视窗:
那么,如果我想要修改下护甲,攻击力的显示效果,那么就可以自定义Editor:
using UnityEngine; using UnityEditor; using System.Collections; [CustomEditor(typeof(MyPlayer))] public class MyPlayerEditor : Editor { public override void OnInspectorGUI() { var target = (MyPlayer)(serializedObject.targetObject); target.attack = EditorGUILayout.IntSlider("攻击力",target.attack,0,100); ProgressBar(target.attack, "攻击力"); target.equipment = EditorGUILayout.ObjectField("装备",target.equipment,typeof(GameObject)); } private void ProgressBar(float value, string label) { Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField"); EditorGUI.ProgressBar(rect, value, label); EditorGUILayout.Space(); } }
是不是一下子就好看了不少,操作性也变强了。这个就是编辑器的魅力所在。
还有一种写法就是,通过SerializedObject的SerializedProperty
我个人不是很推荐,因为更加复杂,但是效果跟上面第一种完全一样:
using UnityEngine; using UnityEditor; using System.Collections; [CustomEditor(typeof(MyPlayer))] public class MyPlayerEditor2 : Editor { SerializedProperty attack; void OnEnable() { attack = serializedObject.FindProperty("attack"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.IntSlider(attack, 0, 100, new GUIContent("攻击力")); ProgressBar(attack.intValue/100, "攻击力"); serializedObject.ApplyModifiedProperties(); } private void ProgressBar(float value, string label) { Rect rect = GUILayoutUtility.GetRect(18, 18, "TextField"); EditorGUI.ProgressBar(rect, value, label); EditorGUILayout.Space(); } }
接下来开始具体学Editor的变量和方法等:
自定义编辑器所需要序列化的物体。看下官方的描述:
A SerializedObject representing the object or objects being inspected.
The serializedObject can be used inside the OnInspectorGUI function of a custom Editor as described on the page about the Editor class.
The serializedObject should not be used inside OnSceneGUI or OnPreviewGUI. Use the target property directly in those callback functions instead.
就是说serializedObject只能在OnInspectorGUI方法里面使用,其他地方是不行的,还有在OnSceneGUI和OnPreviewGUI使用target来代替serializedObject。
标签:images 自定义 function system cal 装备 can 赋值 field
原文地址:http://www.cnblogs.com/CaomaoUnity3d/p/6005044.html