前言:前一陣子筆者寫了驗證器入門指南和 驗證器配置文件設置與使用
這次筆者將介紹自定義全局類型驗證和自定義特性驗證,有了它將極大限度的擴展你的檢測范圍,讓項目中各種不符合規則的類型賦值無所遁藏,只需要一鍵檢測,大大的提高工作效率。
準備工作,創一個自定義類掛在對應物體上
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有幫助,就分享給你的同伴吧~