- Home /
Array in inventory, adding and greater than
So I'm trying to make a simple inventory and I want the player to be able to hit "h" to equip an object if the array is greater than 1, and then subtract 1 from the array so the inventory reads that there are zero lanterns in inventory and then /not/ be able to hit "h" and equip the object again since there are no lanterns in the inventory. Here is my script:
//inventory
static var inventoryArray : int[] = [0,0,0,0,0];
var inventoryText : GameObject;
var firstPersonController:Transform;
var lanturn:GameObject;
function Update () {
inventoryText.guiText.text = "Lantern " + "[" + inventoryArray[0] + "]";
//inventoryArray[0]++;
//inventoryArray[1] += 2;
if (inventoryArray.length >= 1){
if (Input.GetKeyDown("h")){
var go = Instantiate(lanturn) as GameObject;
go.transform.parent = firstPersonController;
print("lemon");
inventoryArray - 1;
}
}
}
If you are looking to resize a collection often then you'll find it easier to use a List(Note this is C# but you can use List in UnityScript with slightly different syntax). Also look at at Eric5h5's answer on this page.
If you are just keeping track of how many lanterns you have with position 0 of your array then go with Uldeim's answer.
Answer by Uldeim · Nov 20, 2014 at 07:09 AM
I'm going to go out on a limb here and make some guesses, because your code is very confusing.
Assumption: You want the number of lanterns to be stored at array position 0. That is, inventoryArray = [5,0,0,0] means you have 5 lanterns currently in your inventory.
In this case, you don't need to check the array length.
You just need:
if (Input.GetKeyDown("h") && inventoryArray[0] > 0){
var go = Instantiate(lanturn) as GameObject;
go.transform.parent = firstPersonController;
print("lemon");
inventoryArray[0] -= 1;
}
I would also correct your spelling of "lantern", since incorrect spellings can really bite you long term.
Thank you so much, I'm sorry for the confusing script and I've also changed the spelling errors.