public class PlayerAttributeExample : MonoBehaviour { //無滑塊的屬性 public int VIPLevel = 0; //特性限定,有滑塊 [Range(0, 10)] public int SliderVIPLevel = 0; }
Range特性的方法實現:
using UnityEngine; using System.Collections; //特性的定義要繼承自PropertyAttribute public class MyRangeAttribute : PropertyAttribute { public float Min;//最小值 public float Max;//最大值 public MyRangeAttribute(float min, float max) { this.Min = min; this.Max = max; } }
using UnityEngine; using System.Collections; using UnityEditor; //繼承PropertyDrawer, 必須放入Editor文件夾下 [CustomPropertyDrawer(typeof(MyRangeAttribute))] public class MyRangeAttributeDrawer : PropertyDrawer { //重載OnGUI方法 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { MyRangeAttribute myRange = attribute as MyRangeAttribute; if (property.propertyType == SerializedPropertyType.Integer) { EditorGUI.IntSlider(position, property, (int)myRange.Min, (int)myRange.Max, label); } else if (property.propertyType == SerializedPropertyType.Float) { EditorGUI.Slider(position, property, myRange.Min, myRange.Max, label); } else { } } }
2.繪制多選
public enum SomeFood { 漢堡 = 0, 雞肉卷 = 1, 薯條 = 3, } //只能單選 public SomeFood MyLoveFood; //多選特性 [EnumListAttribute] public SomeFood MyLoveFoodList;
using UnityEngine; using System.Collections; public class EnumListAttribute : PropertyAttribute { }
using UnityEngine; using System.Collections; using UnityEditor; [CustomPropertyDrawer(typeof(EnumListAttribute))] public class EnumListAttributeDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { property.intValue = EditorGUI.MaskField(position, label, property.intValue, property.enumNames); } }