changing variable based on name of objects in array.

I’m programming a really simple top down shooter to get used to Unity/programming. I use the mouse wheel to select the current weapon. The list of weapons available is an array, and new weapons are added when the player walks over collectibles. That all work great.

On the GUI I’d like to display the weapons in the array and the ammo for each one. The 3 x weapons are: sword, pistol and shotgun.

Here is the code I’m using for the OnGUI:

function OnGUI()
	ps = GetComponent(playerScript);
	var yOffset : float = 35;
    for (var i : int = 0; i <= weapons.Count-1; i++)
      GUI.Label (Rect (10, 10 + yOffset * i, 100, 20), weapons*.name + ":" + ps.pistolAmmo); // <---problem is here.*


The problem is that Whilst I can specify the ammo variable from another script, I can’t work out how to do so dynamically? If the name of the object at index [1] is shotgun for example, how do I specify that the shotgunAmmo variable should be displayed?
Is there some way to achieve this, so I can call (in terrible pseudo-code):
or another simple solution I’m overlooking?

Assuming that weapons is a GameObject Array:

the suggestion alluded to by @getyour411 is a viable alternative…

create a separate script and call it “Weapon”. Give this new script the necessary data members for any given weapon:

var myName : String;
var ammoCount : int;

then attach a copy of the script to each weapon. Use an array of “Weapon” instead, and you have much more control over what is at your fingertips.

(to store the Weapon reference, you would simply use gameObject.[GetComponent]1 for each weapon)


To elaborate… you can access the script from your current GameObject array by replacing:


however, it is better to use GetComponent only in the start function to initialize the variable… Using it constantly in OnGUI will cost big time on performance. You are probably better off using an array of Weapon instead, to solve this issue more simply, in my opinion anyway…
if weapons is an array of Weapon rather than GameObject, you can Add it to the list using:
(based on the example you gave)
since you only call this for one frame it’s not SO bad…