Odin Inspector 系列教程 --- 自定義驗證

前言:前一陣子筆者寫了驗證器入門指南 驗證器配置文件設置與使用
這次筆者將介紹自定義全局類型驗證自定義特性驗證,有了它將極大限度的擴展你的檢測范圍,讓項目中各種不符合規則的類型賦值無所遁藏,只需要一鍵檢測,大大的提高工作效率。


準備工作,創一個自定義類掛在對應物體上

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 系列教程

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。