当一个阵列B的长度是等于另一个变数A里的值。不做额外处理的话,必须随时注意A与B是否相同。为了方便及稳定性,不彷自订一个class包含变数变数A与阵列B,并为此class订做一个PropertyDrawer,如此一来,既自动又正确。先附上图说明before与After。
範例目标 (MeshRenderer上的Materials有几个,阵列长度就是多少)
Before (指定完MeshRenderer后,还需要指定阵列长度)
After (指定完MeshRenderer后,自动根据Materials初始化阵列)
範例程式码 (Sample.cs)
using System;using UnityEngine;public enum State { _1, _2, _3 }// Custom serializable class[Serializable]public class Table{ public MeshRenderer meshRenderer; public State[] states;}public class Sample : MonoBehaviour{ public Table table;}
範例程式码 (TableDrawer.cs)
using UnityEditor;using UnityEngine;[CustomPropertyDrawer(typeof(Table))]public class TableDrawer : PropertyDrawer{ public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); Rect rLabel = position; Rect rField = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label); rField.height = EditorGUIUtility.singleLineHeight; SerializedProperty spMesh = property.FindPropertyRelative("mesh"); SerializedProperty spStates = property.FindPropertyRelative("states"); EditorGUI.PropertyField(rField, spMesh, GUIContent.none); rField.y += EditorGUIUtility.singleLineHeight; MeshRenderer mesh = spMesh.objectReferenceValue as MeshRenderer; if (mesh != null && mesh.sharedMaterials.Length > 0) { spStates.arraySize = mesh.sharedMaterials.Length; for (int i = 0; i < spStates.arraySize; ++i) { SerializedProperty spLipShape = spStates.GetArrayElementAtIndex(i); string labelName = " " + mesh.sharedMaterials[i].name; Rect rt = new Rect(rLabel.x, rField.y, rLabel.width - rField.width, rLabel.height); EditorGUI.LabelField(rt, labelName); EditorGUI.PropertyField(rField, spLipShape, GUIContent.none); rField.y += EditorGUIUtility.singleLineHeight; } } EditorGUI.EndProperty(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { int lineCount = 1; SerializedProperty spMesh = property.FindPropertyRelative("mesh"); MeshRenderer mesh = spMesh.objectReferenceValue as MeshRenderer; if (mesh != null) lineCount += mesh.sharedMaterials.Length; return EditorGUIUtility.singleLineHeight * lineCount; }}