Reputation: 463
At the moment I have a class that requires information from another class, but which class has to be determined at runtime based on other variables.
Effectively, I need my class BUTTON.as to be able to access GUN(1-9).as, without already knowing what number it will be.
The code that I assumed would work is this:
public function enableButton(shortcut:int):void{
trace(ID)
dtf_ammo.text = gun[ID].ammo
refreshThis(shortcut, true)
this.alpha = 1
isActive = true
}
ID is the number of the class (in this case, gun1).
The following does work:
public function enableButton(shortcut:int):void{
trace(ID)
dtf_ammo.text = gun1.ammo
refreshThis(shortcut, true)
this.alpha = 1
isActive = true
}
However, as there are 9 guns and only 1 class for the button I need to be able to use this ID variable to access functions within.
Is this possible, and if not is there a way to do what I'm trying to do here?
Upvotes: 0
Views: 327
Reputation: 1541
You said the 2nd block of code is working. So if you create and array say
var gun:Array = new Array( gun1, gun2,gun3,gun4,gun5,gun6,gun7,gun8,gun9 )
//gun1 to gun9 , being the instances of the Gun class
public function enableButton(shortcut:int):void{
trace(ID)
dtf_ammo.text = gun[ID].ammo
refreshThis(shortcut, true)
this.alpha = 1
isActive = true
}
So, the function enableButton would work fine.
Upvotes: 0
Reputation: 10325
In order to access static properties of a class whose name is only known at runtime, you can use the following code.
getDefinitionByName("gun" + i).ammo
getDefinitionByName
returns the Class object representing the class named by the String passed in. That Class object contains references to all of the static properties of the class.
Upvotes: 1