博客新增音乐播放器,点击打开小组件,切换或暂停音乐。

让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类,用于实现字符限制效果。

    /* ==============================================================================
     * 功能描述:限制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的大小英文)了

posted @   立航  阅读(1913)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示