美文网首页
Odin Inspector 系列教程 --- 自定义验证

Odin Inspector 系列教程 --- 自定义验证

作者: su9257_海澜 | 来源:发表于2019-11-22 11:42 被阅读0次

    前言:前一阵子笔者写了验证器入门指南 验证器配置文件设置与使用
    这次笔者将介绍自定义全局类型验证自定义特性验证,有了它将极大限度的扩展你的检测范围,让项目中各种不符合规则的类型赋值无所遁藏,只需要一键检测,大大的提高工作效率。


    准备工作,创一个自定义类挂在对应物体上

    using Sirenix.OdinInspector;
    using UnityEngine;
    
    public class TestCustomComponent : MonoBehaviour
    {
        [Required("需要一个Obj", MessageType = InfoMessageType.Warning)]
        public GameObject tempObj;
    
        public enum CustomType
        {
            Node,One,Two
        }
        [TestValidatorAttribute]
        public CustomType customType = CustomType.Node;
    
    }
    

    自定义全局类型验证

    全局类型验证:就是不需要向元素添加特性,例如:Required Attribute,在项目中对所有指定类型按照我们想要的规则进行验证,如果不符合规则会弹出我们定义的错误或警告信息

    示例展示

    你只需要编写验证代码、执行验证扫描即可

    示例代码

    using Sirenix.OdinInspector.Editor.Validation;
    [assembly: RegisterValidator(typeof(CustomTypeValidator))]
    
    public class CustomTypeValidator : ValueValidator<TestCustomComponent.CustomType>
    {
        protected override void Validate(TestCustomComponent.CustomType value, ValidationResult result)
        {
            if (value== TestCustomComponent.CustomType.Node)
            {
                result.ResultType = ValidationResultType.Warning;
                result.Message = "需要对CustomType使用除None以外的任何值";
            }
        }
    }
    

    自定义特性验证

    其实就是我们自定义类似Required Attribute的特性

    编写自定义验证特性和对应的验证规则

    using Sirenix.OdinInspector.Editor.Validation;
    using System;
    using System.Reflection;
    
    [assembly: RegisterValidator(typeof(CustomeAttributeValidator))]
    public class TestValidatorAttribute : Attribute { }
    
    /// <summary>
    /// 对此自定义特性的检测机制
    /// </summary>
    
    public class CustomeAttributeValidator : AttributeValidator<TestValidatorAttribute, TestCustomComponent.CustomType>
    {
        protected override void Validate(object parentInstance, TestCustomComponent.CustomType memberValue, MemberInfo member, ValidationResult result)
        {
            try
            {
                //Debug.Log($"parentInstance:{parentInstance}---memberValue:{memberValue}---member:{member}---result:{result}");
                if (memberValue == TestCustomComponent.CustomType.One)
                {
                    throw new ArgumentException($"不能使用{memberValue}");
                }
            }
            catch (ArgumentException ex)
            {
                result.ResultType = ValidationResultType.Error;
                result.Message = "错误或无效的CustomType值: " + ex.Message;
            }
        }
    }
    

    将特性添加到对应的字段上

        [TestValidatorAttribute]
        public CustomType customType = CustomType.Node;
    

    一键运行验证扫描

    以上就是笔者对自定义验证的介绍,如果感觉Odin有帮助,就分享给你的同伴吧~


    更多教程内容详见:革命性Unity 编辑器扩展工具 --- Odin Inspector 系列教程

    相关文章

      网友评论

          本文标题:Odin Inspector 系列教程 --- 自定义验证

          本文链接:https://www.haomeiwen.com/subject/wpmfwctx.html