indexOutOfRangeException:索引超出了数组(单位)的界限



idk我需要做什么才能进入数组的边界。我认为我的数组在我的两个接口之间根本没有计数,或者计数太多,但如果这是它的问题,我只知道这是我的CreateSlots中的数组问题不知道这是否有帮助,但我正在学习一个名为Unity3D的统一教程,该教程为可脚本化的物品库存系统提供装备"代码":

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class StaticInterface : UserInterface
{
public GameObject[] Slots;
public override void CreateSlots()
{
itemsDisplayed = new Dictionary<GameObject, InventorySlot>();
for (int i = 0; i < inventory.Container.Items.Length; i++)
{
var obj = Slots[i]; //this line is the one unity pointed out
AddEvent(obj, EventTriggerType.PointerEnter, delegate { OnEnter(obj); });
AddEvent(obj, EventTriggerType.PointerExit, delegate { OnExit(obj); });
AddEvent(obj, EventTriggerType.BeginDrag, delegate { OnDragStart(obj); });
AddEvent(obj, EventTriggerType.EndDrag, delegate { OnDragEnd(obj); });
AddEvent(obj, EventTriggerType.Drag, delegate { OnDrag(obj); });

itemsDisplayed.Add(obj, inventory.Container.Items[i]);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
public abstract class UserInterface : MonoBehaviour
{
public Player player;
public InventoryObject inventory;
public Dictionary<GameObject, InventorySlot> itemsDisplayed = new Dictionary<GameObject, InventorySlot>();
void Start()
{
CreateSlots();
}
// Update is called once per frame
void Update()
{
UpdateSlots();
}
public abstract void CreateSlots();//this line is the one unity pointed out

我认为你的问题是,库存的大小。Container.Items.Length大于Slots数组的大小,因此Unity尝试从该数组中获取一个不存在的值。因此,也许可以检查,i的大小不大于插槽阵列使用:

if(i < Slots.Lenght)
var obj = Slots[i];
...

最新更新