[Unity编辑器扩展] 重写Inspector面板

8 篇文章 0 订阅

不使用序列化

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();
    }
}

 

 

 

 

 

 

 

 

 


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值