统一的库存系统出现空引用错误

Inventorysystem in unity getting Nullreference error

我对编码很陌生,为了好玩而制作游戏,到目前为止一切顺利。

我现在正在研究库存系统,想用库存槽做一个数组。 我现在的问题是我得到一个 NullReferenceException: Object reference not set to an instance of an object 错误,正确的是 for 循环。可悲的是,我没有看到或理解我的错误。我确实在 Unity 中设置了 det Inventoryslots,目前有 3 个。

*抱歉,如果这是一个愚蠢的问题,我只想学习

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class InventorySlot : MonoBehaviour
{
    public bool isFull;
    public InventorySlot[] inventoryslots;
    private Image Icon;
    private bool foundSlot;
    private Items items;
    private ItemProperties itemProperties;
    public int itemID;
  
    public GameObject inventoryslot;

Items item = new Items();





public void inventorySlot()
{
    
    
}
public void Additem()
{

   item.itemInList = itemID;

   foundSlot = false;

    for (int i = 2; i < inventoryslots.Length; i++)
    {
        if (!inventoryslots[i].isFull)
        {

            Icon.sprite = item.itemSprite;
            inventoryslot.SetActive(true);
            foundSlot = true;
        
        }
    }
    if (foundSlot == false)
    {
        Debug.Log("No space");
    }
}

}

您是否初始化了 inventoryslots 变量? 您需要这样做,就像您在 Items item = new Items();.

中对 item 变量所做的那样