- Home /
Calling 'AddItem' Method giving me error NullReferenceException:
So i have a json. Data base that has id's set to each object. the Method 'AddItem(0)' is suppose to add a Weak health Potion to the UI inventory but gives an error. i have correctly initialized the inventory script using inv = GetComponent<Inventory>();
in the the start and have a variable up top as public Inventory inv;
This is the Keyboard input Script in the Update:
if (Input.GetKeyUp(KeyCode.E))
{
if (ray.hit.transform.tag == "Weak Health Potion")
{
// Gives error Here
inv.AddItem(0);
//------------------
print("Picked up");
Destroy(ray.hit.transform.gameObject);
}
}
And This is the Inventory Script piece:
public void AddItem(int id)
{
Item itemToAdd = database.FetchItemByID (id);
if (itemToAdd.Stackable && CheckIfItemIsInInventory (itemToAdd)) {
for (int i = 0; i < items.Count; i++) {
if (items [i].ID == id) {
ItemData data = slots [i].transform.GetChild(0).GetComponent<ItemData> ();
data.amount ++;
data.transform.GetChild(0).GetComponent<Text> ().text = data.amount.ToString ();
break;
}
}
}
else
{
for (int i = 0; i < items.Count; i ++) {
if (items [i].ID == -1) {
items [i] = itemToAdd;
GameObject itemObj = Instantiate (inventoryItem);
itemObj.GetComponent<ItemData>().item = itemToAdd;
itemObj.GetComponent<ItemData>().amount = 1;
itemObj.GetComponent<ItemData>().slot = i;
itemObj.transform.SetParent (slots [i].transform);
itemObj.transform.position = Vector2.zero;
itemObj.GetComponent<Image> ().sprite = itemToAdd.Sprite;
itemObj.name = itemToAdd.Title;
break;
}
}
}
}
` Im not sure why it is giving error: Please Help me. I am sure its something my tried brain missed.
NullReferenceException: Object reference not set to an instance of an object
KeyboardInput.Update () (at Assets/Scripts/KeyboardInput.cs:50)
I'm sure its the way i have the syntax, but every which why i try gives the same error and wont add the item to the inventory after i press 'e' to pick it up. if I get rid of the error code it destroys the item i am trying to pick up like it suppose to. Whats $$anonymous$$issing? Am i passing the AddItem(0);
correctly to my inventory script? Every Variable for this is public.
If I add the AddItem(0);
in the start in the inventory script; it puts the Weak health potion in the inventory and shows in the GUI UI like it is suppose to. Thanks in advance!