- Home /
Getting info from object within an array
I'm making an inventory system for my game. It's differs from most in the way that the items are pretty much treated like weapons are treated in FPS games. You pick an item up and the character will hold it in front of the camera while running around and you should be able to scroll through the items using the mouse wheel. The inventory system is a modified version of Xeno360's one (http://forum.unity3d.com/threads/53599-My-Contribution-Inventory-System-Free).
What I don't know is how to get the element number and name from an object in my inventory array. I have an int variable called currentWeapon that I wanna sync with the array's element's number and objectname. Ex. I have three objects: Element 0 - dagger, Element 1 - jar, Element 2 - axe. When currentWeapon == 2 I want the axe to be the "active" object.
Parts of the code:
Inventory Script:
var Contents: Transform[];
function AddItem(Item:Transform)
{//Add an item to the inventory.
var newContents=new Array(Contents);
newContents.Add(Item);
Debug.Log(Item.name+" has been added to inventroy");
Contents=newContents.ToBuiltin(Transform);
}
Item Script:
function OnMouseDown()
{//When you click an item
var playersinv=FindObjectOfType(Inventory);//finding the players inv.
playersinv.AddItem(this.transform);
MoveMeToThePlayer(playersinv.transform);//moves the object, to the player
particle.layer = 13;
}
Thanks in advance
Answer by tingham · Feb 08, 2012 at 01:21 PM
You have a couple of options:
If you have access to the transform then you have access to the "name" property of same so (transform.name, transform.parent.name should be illuminating.)
You can keep a separate array of strings where the indexes match. Going this route can be complicated because you take responsibility for keeping the arrays in sync.
Use an array that contains a Hashtable instead of just a plain old GameObject/Transform.
I'm sure there are more, these are the ones that occur to me before coffee so…
Thanks. Barging in on the transform names kinda did the job. I created two new vars (var weaponElement : Transform; var elementName : String;) and aquired the name by making these two lines: weaponElement = Contents[currentWeapon]; elementName = weaponElement.name;.
I wouldn't consider it poor-practice to utilize the data that is already exposed publicly inside of gameObject and Transform; at all. You could just use Contents[currentWeapon].name if you fancy; unless the item has the possibility of going away; in which case you should be bounds checking your array anyhow.
I believe I tried that but got an error telling me it couldn't make a Transform into a String or something. I'll try it the next time I do something similar though, I don't dare touching the script again after getting it to work. :)
It could be that there's some weirdness with accessing members of an array in javascript that I'm not familiar with; I mostly write C#.