0
点赞
收藏
分享

微信扫一扫

Unity(二十四):Attribute特性

窗外路过了谁 2022-02-01 阅读 50

Attribute

在这里插入图片描述

  • Assets/Scripts/CubeScript.cs
    using UnityEngine;
    
    public class CubeScript : MonoBehaviour
    {
        [HpMp("血量", 0, 100)] public int Hp;
        [HpMpAttribute("魔法值", 0, 100)] public int Mp;
    }
    
    public class HpMpAttribute : PropertyAttribute
    {
        public readonly string Name;
        public readonly int Min;
        public readonly int Max;
    
        public HpMpAttribute(string name, int min, int max)
        {
            Name = name;
            Min = min;
            Max = max;
        }
    }
    
  • Assets/Editor/RangIntDrawer.cs
    using UnityEditor;
    using UnityEngine;
    
    [CustomPropertyDrawer(typeof(HpMpAttribute))]
    class HpMpDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            string name = ((HpMpAttribute)attribute).Name;
            int min = ((HpMpAttribute)attribute).Min;
            int max = ((HpMpAttribute)attribute).Max;
            property.intValue = Mathf.Clamp(property.intValue, min, max);
    
            Rect rect1 = new Rect(position.x, position.y + 5, position.width, 20);
            EditorGUI.IntSlider(rect1, property, min, max, $"{name}({property.name})");
    
            float value = ((float)property.intValue - min) / (max - min);
            Rect rect2 = new Rect(position.x, position.y + 30, position.width, 20);
            EditorGUI.ProgressBar(rect2, value, $"{name}{property.intValue}");
        }
    
        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            return 50f;
        }
    }
    
举报

相关推荐

0 条评论