I copied some code I used from one game to another and some of it works correctly and the inventory/ui system i implemented keeps having the same error. This is the example I currently have with this error.
NullReferenceException: Object reference not set to an instance of an object
PlayerInteract.Awake () (at Assets/Scripts/PlayerInteract.cs:16)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInteract : MonoBehaviour
{
Collider2D item;
private Inventory inventory;
[SerializeField] private UI_Inventory uiInventory;
private void Awake()
{
inventory = new Inventory();
uiInventory.SetInventory(inventory);
ItemWorld.SpawnItemWorld(new Vector3(2.5f, 3.5f), new Item { itemType = Item.ItemType.Fireball, amount = 1 });
ItemWorld.SpawnItemWorld(new Vector3(2.0f, 3.5f), new Item { itemType = Item.ItemType.Potion, amount = 1 });
}
//private void Update()
//{
// if (currentInterObj && Input.GetButtonDown("Interact"))
// {
// currentInterObj.SendMessage("DoInteraction");
// }
//}
private void OnTriggerEnter2D(Collider2D collider)
{
ItemWorld itemWorld = collider.GetComponent<ItemWorld>();
if (itemWorld != null)
{
inventory.AddItem(itemWorld.GetItem());
itemWorld.DestroySelf();
}
}
}
The Inventory code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class Inventory
{
public event EventHandler OnItemListChanged;
private List<Item> itemList;
public Inventory()
{
itemList = new List<Item>();
//AddItem(new Item { itemType = Item.ItemType.Fireball, amount = 1 });
//AddItem(new Item { itemType = Item.ItemType.Potion, amount = 1 });
//AddItem(new Item { itemType = Item.ItemType.Fireball, amount = 1 });
//AddItem(new Item { itemType = Item.ItemType.Potion, amount = 1 });
}
public void AddItem(Item item)
{
itemList.Add(item);
OnItemListChanged?.Invoke(this, EventArgs.Empty);
}
public List<Item> GetItemList()
{
return itemList;
}
}
The original video that I took the code from is a Code Monkey video.