我的库存有问题。我使用一些Foldouts为Inspector编写了一个编辑器(使库存系统更具可读性)。我还有一个常量Int,它定义了我的库存槽数。问题是,当我更改const int时,Tto让我说6我从InventoryEditor类中得到多个错误。当const int为4或更小时,一切正常。但是,如果我将数字更改为更高的数字,我会收到如下错误:IndexOutOfRangeException,NullReferenceException等等(我把确切的日志放在问题的下面)。库存类应该没问题我很确定问题出在InventoryEditor类中。
以下是代码:
public class Inventory : MonoBehaviour {
public const int itemNumCap = 6;
[SerializeField]
private Item[] items = new Item[itemNumCap];
[SerializeField]
private Image[] itemsImg = new Image[itemNumCap];
public void AddItem(Item itemToAdd)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i] == null)
{
items[i] = itemToAdd;
itemsImg[i].sprite = itemToAdd.sprite;
itemsImg[i].enabled = true;
return;
}
}
}
public void RemoveItem(Item itemToRemove)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i] == itemToRemove)
{
items[i] = null;
itemsImg[i].sprite = null;
itemsImg[i].enabled = false;
return;
}
}
}
}
和InventoyEditor:
[CustomEditor(typeof(Inventory))]
public class InventoryEditor : Editor
{
private bool[] showItemSlots = new bool[Inventory.itemNumCap];
private SerializedProperty itemImagesProperty;
private SerializedProperty itemsProperty;
private const string inventoryPropItemImagesName = "itemsImg";
private const string inventoryPropItemsName = "items";
private void OnEnable()
{
itemImagesProperty = serializedObject.FindProperty(inventoryPropItemImagesName);
itemsProperty = serializedObject.FindProperty(inventoryPropItemsName);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
for (int i = 0; i < Inventory.itemNumCap; i++)
{
ItemSlotGUI(i);
}
serializedObject.ApplyModifiedProperties();
}
private void ItemSlotGUI(int index)
{
EditorGUILayout.BeginVertical(GUI.skin.box);
EditorGUI.indentLevel++;
showItemSlots[index] = EditorGUILayout.Foldout(showItemSlots[index], "Item slot " + index);
if (showItemSlots[index])
{
EditorGUILayout.PropertyField(itemImagesProperty.GetArrayElementAtIndex(索引));
EditorGUILayout.PropertyField(itemsProperty.GetArrayElementAtIndex(索引));
}
EditorGUI.indentLevel--;
EditorGUILayout.EndVertical();
}
}
我希望你们能以某种方式帮助我。
以下是错误日志:
IndexOutOfRangeException: Array Index is out of Range.
InventoryEditor.ItemSlotGUI (Int32 Index)
Retrieving Array Element thatw as out of bounds
UnityEditor.SerialziedProperty: GetArrayElementAtIndex (Int32)
NullReferenceException: Object reference not set to an Instance of an Object
UnityEditor.PropertyHandler.OnGUILayout(UnityEditor.SerializedProperty property, UnityEngine.GUIContent label, Boolean includeChildren, UnityEngine.GUILayoutOption[] options
的外观