- Home /
Inventory AddItem help
I am making an inventory and i dont understand why i cant do this. Item is a different script with all the variables in it such as: itemName, itemDescription, ect. So why cant i add an new Item? it tells me that i can add a script this way. But im not trying to add the script, im just trying to fill it with the type script.
public Item[ , ] inventory; **Item is a different Script with all the item variables**
void Start ()
{
inventory = new Item[across, down];
for (int x=0; x<5; x++)
{
AddItem(new Item());
}
}
void AddItem (Item item)
{
for (int x=0; x<across; x++)
{
for (int y=0; y<down; y++)
{
if (inventory[x, y] == null)
{
inventory[x, y] = item;
return;
}
if (inventory[x, y].itemName == item.itemName)
{
inventory[x, y].itemAmount += item.itemAmount;
}
}
}
}
Can you copy and paste the exact error that appears in the console please.
Also include the Item class. $$anonymous$$y suspicion is that it is a $$anonymous$$onoBehaviour and indeed you cannot create an instance of a $$anonymous$$onoBehaviour using the 'new' keyword.
Hey, this might help you out: https://www.youtube.com/watch?v=$$anonymous$$LaGkc87dDQ
Answer by Kastenessen · Jan 15, 2015 at 05:12 AM
Well I think all your script does there is create and add new items to the item array at the top. If you have a seperate script, perhaps on another gameobject, then you have a few choices i think. Im not an expert Im new to this too, but I think you'd either have to use get component on for the gameobject that has the inventory script and access it that way, or you could use static variables or arrays I guess. Make the inventory script item array static so you can access it from anywhere, then you can add for all your life. Oh if your adding while in play, make sure its a list and not an array. And if you destroy or take out objects, then to get around null exceptions, first check if there is an item at the arrays index then if there is do something, and if not then it will ignore it and not throw and exception.
Your answer
Follow this Question
Related Questions
Decorator pattern for inventory item class 0 Answers
Issues with Inventory script 0 Answers
Count object list duplicates 1 Answer
Multiple Cars not working 1 Answer
How to add item to my inventory when I pick them up? 1 Answer