So I want to make an inventory system, simply because I have never done it before, I thought of all the things I would like it to do, to equip weapons from your inventory and to collect items from dead enemies, also to destroy items…
First up I made an item class, fairly simple with one stat - damagevalue, it’s icon as a sprite and it’s ID which I will explain later on why it is useful.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Item{
public int ID;
public GameObject itemObject;
public Sprite Icon;
public float DamageValue;
}
Then I made a Slot Script for storing the items within slots in my bag, the UI of the bag consists of a panel on which I have placed on a 4x4 table made up from “Image” UI elements. Each slot has an Image, which is like a reference to the Image appropriate to the specific slot. As well as an item, which is the item that the slot contains;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[System.Serializable]
public class Slot {
public Item SlotItem;
public Image SlotImage;
}
Now I have an itemdatabase script, which is actually just a script in which i have a list of all available items, as a List of the “Item” class.
Last of all, is the script that I am having problems with, the Inventory script itself:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Inventory : MonoBehaviour {
public ItemDatabase dbRef; //A reference to the itemdatabase script
public List<Slot> BagSlots = new List<Slot>(); //List of all the slots in my bag
bool invUpdated;
void Start(){
dbRef = GameObject.FindGameObjectWithTag ("itemDatabase").GetComponent<ItemDatabase> (); //Setting the reference through the itemDB tag
}
void Update(){
UpdateInventory()
}
void UpdateInventory(){
//This function is used as an update to get called all the time, it is actually what controls the slots of the specific item
for(int i = 0; i< BagSlots.Count; i++){ //Starting from the first element in BagSlots, till the last
BagSlots[i].SlotItem = dbRef.itemDatabase[BagSlots[i].SlotItem.ID]; // So I am setting each item to be equal to the Item with the index 'ID'
//The ID of an item is used for me to find the item in the database..
BagSlots [i].SlotImage.sprite = BagSlots [i].SlotItem.Icon; //In this line I am just changing the Sprite, the "icon" in the UI;
}
}
}
Now unity throws me an error “ArgumentOutOfRangeException” each time the loop happens and I can’t figure out why