首页 > 解决方案 > 统一的Inventorysystem得到Nullreference错误

问题描述

我对编码很陌生,并且制作有趣的游戏,到目前为止一切顺利。

我现在正在研究库存系统,想从库存槽中做一个数组。我现在的问题是我得到一个 NullReferenceException: Object reference not set to an instance of an object error,就在 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");
    }
}

}

标签: c#unity3dnullreferenceexception

解决方案


你初始化inventoryslots变量了吗?你需要这样做,就像你对item变量 in所做的那样Items item = new Items();


推荐阅读