讓Unity的Inspector面板支持字符限制(restrict)功能

今天在優化紅點組件,筆者打算將紅點id由10進制改成16進制處理,就打算將紅點id字段由uint類型改爲string類型,用於填寫16進制的字符(由於在Inspector面板裏,uint/int類型字段不能直接填寫16進製表示的數字),且但願限制該字段的輸入限制,僅限於填寫0-9A-Fa-f等16進制字符串,但unity並無提供任何PropertyAttribute類來限制字符輸入,達到相似於as3 text組件的restrict效果。所以筆者自定義了一個RestrictAttribute類,用於實現字符限制效果。ide

/* ==============================================================================
     * 功能描述:限制string字段的輸入類型
     * 創 建 者:shuchangliu
     * ==============================================================================*/

    using System.Text.RegularExpressions;
    using UnityEngine;
    #if UNITY_EDITOR
    using UnityEditor;
    #endif

    public class RestrictAttribute : PropertyAttribute
    {
        public string restrict;
        // Use this for initialization
        public RestrictAttribute(string restrict)
        {
            this.restrict = restrict;
        }
    }

    #if UNITY_EDITOR
    [CustomPropertyDrawer(typeof(RestrictAttribute))]
    public class RestrictDrawer : PropertyDrawer
    {
        public override float GetPropertyHeight(SerializedProperty property,
                                                GUIContent label)
        {
            return EditorGUI.GetPropertyHeight(property, label, true);
        }

        public override void OnGUI(Rect position,
                                   SerializedProperty property,
                                   GUIContent label)
        {
            RestrictAttribute a = attribute as RestrictAttribute;

            EditorGUI.PropertyField(position, property, label, true);
            string v = property.stringValue;
            v = Regex.Replace(v, @"[^" + a.restrict + "]*", "");
            property.stringValue = v;
        }

    }
    #endif

public class Test : MonoBehaviour
    {
        [Restrict("0-9a-fA-F")]
        public string pid;
    }

在字段前加上[Restrict(string str)]參數,pid就只能夠輸入16進制數字(0-9及a-f的大小英文)了優化

相關文章
相關標籤/搜索