- Home /
How to get the number of variables in a class, and then call the variable by its number.
So basically I want to know if I can use a class as an array of variables, now I don't need to add variables to the class just get the total number of variables in it, and then call each variable by that number. And if not could I make the variables in a class part of a function and then do it that way.
Like here
public class SingleCharacterScript extends MonoBehaviour { public class Stuff { public var bullets : int; public var grenades : int; public var rockets : int;
public function Stuff(bul : int, gre : int, roc : int)
{
bullets = bul;
grenades = gre;
rockets = roc;
}
}
then just do eather
class.Stuff.length
or
Stuff.length
??? I have been searching the api and can't find anything.
What you describe as SilentSin says is an Array. Arrays are basic program$$anonymous$$g functionality and are not covered by the Unity API. The scripting tutorials have a lecture on them though: http://unity3d.com/learn/tutorials/modules/beginner/scripting
Arrays are lecture number 25, but I do recommend to start at the beginning.
It's like taping two live cats together. Sure, there's a best way to do it. But whatever it is you're trying to get done, there are far superior tapeless solutions.
Usually "look up by number" problems are best solved with arrays. Usually. I'm not sure the best place to learn them is Unity tutorials (people have been explaining arrays pretty well for 40 years.)
Answer by SilentSin · Jan 15, 2015 at 06:12 AM
The best way would be to use an actual array. Just make a bunch of int constants like bullets = 0, grenades = 1, rockets = 2 and use them to index the array. Or you could make an enum and use it to index the array.
Or you could make an indexer that takes an int and uses a switch to determine which variable to get or set.
Or you could use reflection, which is quite complicated, would probably take lots of effort to learn and implement, and would be far less efficient than any other approach.