Ok so ive been following a tutorial on how to make inventorys by inScope studios, anyways I got to about an hour in the video, and I followed step by step, but unity gives me an error when I attempt to pick an item up. In his video he doesnt get the error and is able to pick the item up perfectly, So i spent 4+ hours going back and through my code and his code and I nailed down every line exactly but I still get the error. Heres the error:
“NullReferenceException: Object reference not set to an instance of an object
Slot.get_IsEmpty () (at Assets/Scripting/Slot.cs:18)
Inventory.placeEmpty (.ItemScript item) (at Assets/Scripting/Inventory.cs:101)
Inventory.AddItem (.ItemScript item) (at Assets/Scripting/Inventory.cs:87)
KeyBinding.checkPickup () (at Assets/Scripting/KeyBinding.cs:75)
KeyBinding.Update () (at Assets/Scripting/KeyBinding.cs:31)”
And it targets this script specifically:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class Slot : MonoBehaviour {
private Stack<ItemScript> items;
public Text stackTxt;
public Sprite SlotEmpty;
public Sprite SlotHighlight;
public bool IsEmpty
{
get { return items.Count == 0; }
}
void start()
{
items = new Stack<ItemScript>();
RectTransform slotRect = GetComponent<RectTransform>();
RectTransform txtRect = GetComponent<RectTransform>();
int txtScaleFactor = (int)(slotRect.sizeDelta.x * 0.60); //calc scale factor
stackTxt.resizeTextMaxSize = txtScaleFactor; //set max scale factor
stackTxt.resizeTextMinSize = txtScaleFactor; //set min scale factor
txtRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, slotRect.sizeDelta.y);
txtRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, slotRect.sizeDelta.x);
}
private void ChangeSprite(Sprite neutral, Sprite highlight)
{
GetComponent<Image>().sprite = neutral;
SpriteState st = new SpriteState();
st.highlightedSprite = highlight;
st.pressedSprite = neutral;
GetComponent<Button>().spriteState = st;
}
void Update()
{
}
public void AddItem(ItemScript item)
{
items.Push(item);
if (items.Count > 1) //Update stack number if > 1
{
stackTxt.text = items.Count.ToString(); //writes the amount of items and converts to str
}
ChangeSprite(item.spriteNeutral, item.spriteHighlighted); //change sprite from slot to whatever we add
}
}
Note that
public bool IsEmpty
{
get { return items.Count == 0; }
}
is where the problem is apparently coming from.
I get the error whenever I collide with the object im trying to pick up, and i’ve even tried picking it up with a raycast, and I still receive the exact same error.
P.S (Another problem im encountering is whenever I reboot this unity project my vertical axis on my FPS controller gets locked and I cant look up or down, my only work around was to delete the controller and put a new one in, even so its still incredibly annoying.)