Hi all I’m pretty new to unity and c# coding. I’m trying to make a simple inventory system following along with a tutorial, but I’ve run into an issue that I can’t figure out. The error log is returning a NullReferenceException: Object reference not set to an instance of an object error and I’ve triple checked my code and it’s exactly the same as the tutorial so I’m at a bit of a loss. Here’s what I have that I think pertains to the issue:
PlayerController.cs
[SerializeField] private UI_Inventory uiInventory;
private Inventory inventory;
private void Awake()
{
anim = GetComponent();
rb = GetComponent();
jump = new Vector3(0.0f, 1.0f, 0.0f);
inventory = new Inventory();
uiInventory.SetInventory(inventory);
}
UI_Inventory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UI_Inventory : MonoBehaviour
{
private Inventory inventory;
private Transform itemSlotContainer;
private Transform itemSlotTemplate;
private void Awake(){
itemSlotContainer = transform.Find(“itemSlotContainer”);
itemSlotTemplate = itemSlotContainer.Find(“itemSlotTemplate”);
}
public void SetInventory(Inventory inventory){
this.inventory = inventory;
RefreshInventoryItems();
}
private void RefreshInventoryItems(){
int x = 0;
int y = 0;
float itemSlotCellSize = 30f;
foreach (Item item in inventory.GetItemList()){
RectTransform itemSlotRectTransform = Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent();
itemSlotRectTransform.gameObject.SetActive(true);
itemSlotRectTransform.anchoredPosition = new Vector2(x * itemSlotCellSize, -y * itemSlotCellSize);
Image image = itemSlotRectTransform.Find(“image”).GetComponent();
image.sprite = item.GetSprite();
x++;
if (x > 4){
x = 0;
y++;
}
}
}
}
Inventory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory
{
private List itemList;
public Inventory() {
itemList = new List();
AddItem(new Item { itemType = Item.ItemType.Flower, amount = 1});
AddItem(new Item { itemType = Item.ItemType.Bug, amount = 1});
AddItem(new Item { itemType = Item.ItemType.Water, amount = 1});
AddItem(new Item { itemType = Item.ItemType.Jar, amount = 1});
}
public void AddItem(Item item){
itemList.Add(item);
}
public List GetItemList(){
return itemList;
}
}
Please help! I’ll upload my files as well for the whole thing
7705684–965488–Inventory.cs (679 Bytes)
7705684–965491–Item.cs (591 Bytes)
7705684–965494–ItemAssets.cs (379 Bytes)
7705684–965497–PlayerController.cs (4.08 KB)
7705684–965500–UI_Inventory.cs (1.29 KB)
