- Home /
How to determine what type of class is being interated through in an array of multiple classes
I have an inventory script that contains multiple types of item classes, for example Weapon, Ammo, or Armor and I'm trying to iterate through the inventory and discover what type of class is currently being iterated through:
class Weapon { var Icon : Texture; var Name : String; var AmmoLoaded : String; }
class Ammo { var Icon : Texture; var Name : String; var Quantity : int; }
function OnGUI() { for( var i = 0; i < inventory.length; i ++ in inventory ) { var currentItem = inventory[i]; if (currentItem == Weapon) GUILabel( Rect(0,0,20,20), currentItem.Name); if (currentItem == Ammo) GUILabel( Rect(50,0,20,20), currentItem.Name); } }
Here I'm trying to get each type of item to appear in a different place on the screen, but even if I print(currentItem) and it prints out "Weapon" or "Ammo" in the console, it doesn't understand if (currentItem == Weapon).
Answer by Mike 3 · Dec 18, 2010 at 03:33 AM
Use the is keyword:
if (currentItem is Weapon)
Edit (js):
if ((currentItem as Weapon) != null)
or
if (currentItem.GetType() == Weapon)
Sorry but this is throwing an exception: expecting ), found 'is'.
I think the 'is' keyword is for C# and not javascript?
Oh sorry, I misread the above as c# for some reason. I'll add in some JS examples that I can think of
Your answer
Follow this Question
Related Questions
Ways to optimize this code? iterate through inventory 0 Answers
Trying to create an class array with two properties 1 Answer
When using input, array.Add replaces the last member 1 Answer
How can I parent each item from one array to each item in another array? 1 Answer
Storing Prefab in an Array 1 Answer