Hello everyone, I’m facing a (apparently) common problem with unity which is this error:
Object reference not set to an instance of an Object C#
However, solutions found here and on the web do not really help me, as most of them is “you havent added component” or other simple things and I have not found anything that simple in my code. So here it is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour
{
public bool[] isFull;
public GameObject[] slots;
public Item[] items;
[SerializeField] ItemSprite itemSprite;
public void UpdateInventory()
{
for (int i = 0; i < isFull.Length; i++)
{
if (!isFull[i])
{
slots[i].transform.GetChild(0).GetComponent<Image>().sprite = itemSprite.GetSprite(Item.ItemType.Empty);
Debug.Log("Empty field");
}
else
{
slots[i].transform.GetChild(0).GetComponent<Image>().sprite = itemSprite.GetSprite(items[i].itemType);
Debug.Log("Non-empty field");
}
}
}
void Start()
{
items = new Item[isFull.Length];
for (int i = 0; i < isFull.Length; ++i)
{
isFull[i] = false;
items[i].SetItem(Item.ItemType.Empty, 0);//Object reference not set to an instance of an object
}
UpdateInventory();
}
}
it also uses this code from another file:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item
{
public enum ItemType
{
Empty,
BronzeBar,
SilverBar,
GoldBar,
DiamondBar
}
public void SetItem(ItemType newItemType, int newAmount)
{
itemType = newItemType;
amount = newAmount;
}
public ItemType itemType;
public int amount;
}
any help will be appreciated!
also hope I haven’t done anything wrong in means of this post, however if I did - please tell me.