Trying to create a system where the InventoryHandler reads an array of the names of items in your inventory, sends them to an ItemList via method CompareItem(), and receives GameObjects of type Item in return, which it can then use to instantiate the items in the scene. I am, however, getting a NullReferenceException on the names of the items being sent. What am I missing?
public class InventoryHandler : MonoBehaviour {
public string [,] inventory = new string[10, 4];
public Transform place; //Used for locating where to instantiate items
public float spacing = 1;// Ditto
ItemList itemlist = new ItemList();
void Start () {
for(int i = 0; i < inventory.GetLength(0); i++)
for(int j = 0; j < inventory.GetLength(1); j ++){
inventory[i, j] = "it1"; // Fills inventory array with items.
}
}
void Update () {
for(int i = 0; i < inventory.GetLength(0); i++)
for(int j = 0; j < inventory.GetLength(1); j ++)
{
string current = inventory[i, j];
Item item = itemlist.CompareItem(current); //Exception thrown here.
Instantiate(item, new Vector3(place.position.x + (spacing * i), place.position.y - (spacing * j)), Quaternion.identity);
}
}
public class ItemList : MonoBehaviour {
public Item[] items;
public Item empty;
public Item it1; //These are defined in the Inspector.
public Item it2;
// Use this for initialization
void Start () {
items = new Item[]{
it1,
it2
//etc. etc.
};
}
public Item CompareItem(string nameToCheck){
for(int i = 0; i < items.GetLength(0); i++)
if (items[0].itemName == nameToCheck){ //Same exception also thrown here.
return items[0];
}
return null;
}
}
public class Item : MonoBehaviour {
public string itemName;
}
public class Item1Inventory : Item {
void Start(){
itemName = “it1”;
}
}
The error message is:
NullReferenceException: Object reference not set to an instance of an object
ItemList.CompareItem (System.String nameToCheck) (at Assets/ItemList.cs:34)
InventoryHandler.Update () (at Assets/InventoryHandler.cs:25)