【Unity-Tool】特性扩展:条件控制Inspector属性显隐

0 前言

今天遇到了一个需求,以下举例进行描述:
现有一个自定义类型Test,它有一个枚举类型变量speciesType和一个float类型变量height。

Test.cs

using UnityEngine;
public enum SpeciesType
{
   
    People,
    Null,
}
public class Test : MonoBehaviour
{
   
    [SerializeField]
    public SpeciesType speciesType;
    public float height = 160.0f;
}

height变量仅在speciesType==SpeciesType.People时用来描述身高,也就是说,height变量仅在条件满足时起作用。
因此,我希望height变量仅在条件满足时才显示在Inspector窗口中。

理想的情况:
当speciesType的值为SpeciesType.People时:

当speciesType的值为其他时:
在这里插入图片描述

1 工具相关代码

1.UnityEditorHelper.cs
该脚本主要是为了辅助获取对应的属性值。

#if UNITY_EDITOR
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
public static class UnityEditorHelper
{
   
    public static T GetActualObject<T>(this SerializedProperty property) {
   
        try {
   
            if (property == null)
                return default(T);
            var serializedObject = property.serializedObject;
            if (serializedObject == null) {
   
                return default(T);
            }

            var targetObject = serializedObject.targetObject;

            var slicedName = property.propertyPath.Split('.').ToList();
            List<int> arrayCounts = new List<int>();
            for (int index = 0; index < slicedName.Count; index++) {
   
                arrayCounts.Add(-1);
                var currName = slicedName[index];
                if (currName.EndsWith("]")) {
   
                    var arraySlice = currName.Split('[', ']');
                    if (arraySlice.Length >= 2) {
   
                        arrayCounts[index - 2] = Convert.ToInt32(arraySlice[1]);
                        slicedName[index] = string.Empty;
                        slicedName[index - 1] = string.Empty;
                    }
                }
            }

            while (string.IsNullOrEmpty(slicedName.Last())) {
   
                int i = slicedName.Count - 1;
                slicedName.RemoveAt(i);
                arrayCounts.RemoveAt(i);
            }

            return
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值