- Home /
Need help with array script
var inv = new Array(35);
function Awake() {
var gos = GameObject.FindGameObjectsWithTag("Item");
for (var go : GameObject in gos) {
var distanceToMe : float = Vector3.Distance(transform.position, go.transform.position);
if(distanceToMe < range)
inv.Add(go);
print(inv[0]);
}
}
I am working on an inventory array. I am trying to have it pickup a gameobject with the tag item and store it in the array. This is what I have so far but it doesn't print that there is anything in the array. I'm not sure what I'm doing wrong and I still don't know how to make it add to inventory gui or how I would be able to add it to the world again.
Answer by Owen-Reynolds · Jul 18, 2011 at 02:26 PM
You're missing the {} in the last if. When you check the 1st item, it is probably a duck, way in the corner, so isn't added, then you print the 1st thing in inv
, which crashes since inv
is empty.
But, inventory is trickier than this. You probably want the item to vanish when it is picked up (Destroy), then reappear when you put it down (Instantiate.) So, somehow you'll want items in inventory to "know about" their prefabs. Alternately, you can teleport picked up items to -999 and t'port back on a drop.
Will the inventory show as names or icons? If you want similar items to stack, then each "inventory item" will have a name (or an icon), a count and the prefab/list of gameObjects.
You might start small, like picking up power-ups. I suspect you will need to learn how to write classes and/or structs to do much more. You might also look around to see the approach other people have taken.