不使用序列化
using UnityEngine;
using UnityEditor;
public class Gun : MonoBehaviour
{
public int damage = 50;
public float hp = 100;
public GameObject gun;
}
//不使用序列化
[CustomEditor(typeof(Gun))]
public class GunEditor : Editor
{
Gun gun;
private void Awake()
{
gun = (Gun)target;
}
public override void OnInspectorGUI()
{
gun.damage = EditorGUILayout.IntSlider("伤害", gun.damage, 1, 100);
//绘制滑动条
MyGunEditor.ProgressBar(gun.damage / 100.0f, "伤害值");
gun.hp = EditorGUILayout.Slider("血量", gun.hp, 1, 100);
MyGunEditor.ProgressBar(gun.hp / 100.0f, "生命值");
//EditorUtility.IsPersistent:对象是否在磁盘上,如果在场景中返回false
bool allowSceneObjects = !EditorUtility.IsPersistent(target);
gun.gun = (GameObject)EditorGUILayout.ObjectField("机枪", gun.gun, typeof(GameObject), allowSceneObjects);
}
}
使用序列化
using UnityEngine;
using UnityEditor;
public class MyGun : MonoBehaviour
{
public int damage = 75;
public int armor = 25;
public GameObject gun;
}
/// <summary>
/// 序列化对象
/// </summary>
[CustomEditor(typeof(MyGun))] //表名该类是某一个类的编辑器类
[CanEditMultipleObjects] //使该编辑器支持多对象
public class MyGunEditor : Editor
{
SerializedProperty damageProp;
SerializedProperty armorProp;
SerializedProperty gunProp;
private void OnEnable()
{
damageProp = serializedObject.FindProperty("damage");
armorProp = serializedObject.FindProperty("armor");
gunProp = serializedObject.FindProperty("gun");
}
public override void OnInspectorGUI()
{
//总是更新Inspector面板
serializedObject.Update();
//要编辑的属性,左值,右值,标签
EditorGUILayout.IntSlider(damageProp, 1, 100, new GUIContent("伤害"));
if (!damageProp.hasMultipleDifferentValues)
ProgressBar(damageProp.intValue / 100.0f, "伤害值");
EditorGUILayout.IntSlider(armorProp, 0, 100, new GUIContent("护甲"));
if (!armorProp.hasMultipleDifferentValues)
ProgressBar(armorProp.intValue / 100.0f, "护甲值");
EditorGUILayout.PropertyField(gunProp, new GUIContent("机枪"));
serializedObject.ApplyModifiedProperties();
}
public static void ProgressBar(float value, string label)
{
Rect rect = GUILayoutUtility.GetRect(18, 18);
EditorGUI.ProgressBar(rect, value, label);
EditorGUILayout.Space();
EditorGUILayout.Space();
}
}