I’m trying to go through the current items in an inventory and return their names (Inventory.ListItems()). The rest of the script works apart from this piece. An error is returned (Object reference not set to an instance of an object) for some reason.
InventorySystem.js:
var item : Item;
var inventory : Inventory;
class Inventory {
private var size : int = 20;
private var occupiedSlots : int = 0;
private var items : Item[] = new Item;
function ListItems () {
for(var i = 0; i < occupiedSlots; i ++){
Debug.Log(items.GetName(items*)); //Line where it errors at.*
-
}* -
}*
-
function AddItem (item : Item) {*
-
if(occupiedSlots < size){* -
items[occupiedSlots + 1] = item;* -
occupiedSlots ++;* -
}* -
else{* -
Debug.Log("Inventory full");* -
}* -
}*
}
class Item {
-
var icon : Texture2D;*
-
var name : String;*
-
var description : String;*
-
function GetName (item : Item) : String{*
-
return item.name;* -
}*
}
function Start () {
-
inventory = new Inventory();*
-
item = new Item();*
-
item.name = “test”;*
-
item.description = “A test item”;*
-
inventory.AddItem(item);*
}
function Update () {
-
if(Input.GetKeyDown(KeyCode.Q)){*
-
inventory.AddItem(item);* -
}*
-
if(Input.GetKeyDown(KeyCode.E)){*
-
inventory.ListItems();* -
}*
}
Thanks for reading.
If you want to use this code feel free to do so. Just please reference that is made by me (Sam Farhan).
Fix:
function AddItem (item : Item) { -
if(occupiedSlots < size){* -
items[occupiedSlots] = item;* -
Debug.Log("Added " + item.name + " to slot " + occupiedSlots);* -
occupiedSlots ++;* -
}* -
else{* -
Debug.Log("Inventory full");* -
}* -
}*
And:
class Item { -
var icon : Texture2D;*
-
var name : String = null;*
-
var description : String = null;*
-
function GetName (item : Item) : String{*
-
return name;* -
}*
}