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