我正在制作一款带有库存系统的游戏,主库存和工具栏是独立的游戏对象。当库存是满的,它不知道开始添加新的项目到工具栏,并返回null,因为它找不到一个空槽。我试图运行一个函数,告诉游戏添加任何新项目到工具栏,如果它可以当查找索引函数返回null,但我不知道这是如何做到的。我需要知道如何运行一个函数时列表。查找索引返回null
thanks in advance.
FindIndex
never返回null
。如果没有找到任何项,则返回-1
。
所以你可以检查
var index = uiItems.FindIndex(i => i.item == null);
if(index > -1)
{
UpdateSlot(index, item);
}
else
{
Debug.LogWarning("All slots full!");
}
或者不是通过索引,而是检查是否有空闲槽并使用LinqFirstOrDefault
using System.Linq;
...
var freeSlot = uiItems.FirstOrDefault(i => i.item == null);
if(freeSlot != null)
{
UpdateSlot(freeSlot, item);
// Or if you still rather want to go by index
//UpdateSlot(uiItems.IndexOf(freeSlot), item);
}
else
{
Debug.LogWarning("All slots full!");
}
,当然相应地使你的方法签名
void UpdateSlot(Slot, Item)
而不是