我正在尝试在unity中创建一个可重新排序的列表,该列表存储了一个自定义类列表:
using System;
using UnityEngine;
[Serializable]
public struct OnboardingItemData
{
[Tooltip("The hint gameobject")]
public GameObject prefab;
[Tooltip("The object this hint is highlighting")]
public GameObject target;
}
这个类在列表中:
using System;
using System.Collections.Generic;
using UnityEngine;
public class OnboardingItemList : MonoBehaviour
{
public List<OnboardingItemData> list = new List<OnboardingItemData>();
private void Update()
{
Debug.Log("List count: " + list.Count);
}
public void Refresh()
{
for (int i=0; i < list.Count; i++)
{
if (list[i].prefab != null)
{
list[i].prefab.GetComponent<OnboardingItemClickHandler>().id =
i;
}
}
}
public virtual void Show(int id)
{
Debug.Log(list.Count);
list[id].prefab.SetActive(true);
}
public virtual void Hide(int id)
{
list[id].prefab.SetActive(false);
}
}
此列表如下所示:
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
[CustomEditor(typeof(OnboardingItemList))]
public class OnboardingEditor : Editor
{
private ReorderableList list;
private void OnEnable()
{
list = new ReorderableList(serializedObject,
serializedObject.FindProperty("list"),
true, true, true, true);
list.drawElementCallback =
(Rect rect, int index, bool isActive, bool isFocused) => {
var element =
list.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
EditorGUI.PropertyField(
new Rect(rect.x, rect.y, 200,
EditorGUIUtility.singleLineHeight),
element.FindPropertyRelative("prefab"), GUIContent.none);
EditorGUI.PropertyField(
new Rect(rect.x + 250, rect.y, 200,
EditorGUIUtility.singleLineHeight),
element.FindPropertyRelative("target"), GUIContent.none);
};
}
public override void OnInspectorGUI()
{
list.DoLayoutList();
serializedObject.ApplyModifiedProperties();
OnboardingItemList myScript = (OnboardingItemList)target;
if (GUILayout.Button("Apply"))
{
myScript.Refresh();
}
}
}
现在,在我的场景中,有一些UI元素在OnboardingItemList上调用Show()和Hide()函数。问题是我得到一个超出范围的异常,所以我在Update()中放了一个Debug.Log,我看到列表的计数不断变化。一帧表示2,下一帧0,它不断来回变换。我假设有些东西会不断将列表重置为新列表,编辑器会继续为其分配自定义编辑器的值。怎么能修好?