LupusAlbus
LupusAlbus

Reputation: 11

Actionscript 3: How do I create a dynamic import statement?

I have a file structure that specifies the weapon type ["Axe","Mace","Staff",Sword"], and I want to import a specific .as file from within that folder, depending on the value of a variable (Group).

What i'd like to do is something like this: Weapon.[Group].Enchantments (obviously not exactly that; that doesn't work)

For example, if Group = "Axe"; I want to import Weapon.Axe.Enchantments.

But if Group = "Mace"; I want to import Weapon.Mace.Enchantments.

Is this possible with AS3, without creating a bunch of if statements or a switch, and handling them accordingly?

package Weapons {

public class Weapon {
    import Math.random;
    import Math.floor;
    import Weapons.*;

    public var groups:Array = ["Axe","Mace","Staff","Sword"];

    public var Group:String;
    public var Quality:Object;
    public var Enchantment:Object;
    public var Material:Object;
    public var Type:Object;
    public var Profession:Object;

    public function Weapon() {
        // constructor code
        Group = Math.floor(Math.random*groups.length);
        var i:Number;
        Enchantment = Weapons.[Group].Enchantments[i]
    }

}

}

Thanks in advance.

Upvotes: 1

Views: 135

Answers (2)

Nambew
Nambew

Reputation: 640

The import keyword is only use for the compilation of your project, you cannot use the import at runtime. You can dynamicly instantiate your class at runtime by using ApplicationDomain for that.

var myClass:Class = ApplicationDomain.currentDomaint.getClassDefinition("com.package.YourClass"); var myWeapon:Weapon = new myClass() as Weapon;

But I don't think you really need that. Normally the "Axe","Mace","Staff","Sword" classes should extend Weapon class. You can use the Factory Design Pattern to get the right class with string.

http://en.wikipedia.org/wiki/Factory_%28object-oriented_programming%29

Upvotes: 4

m1gu3l
m1gu3l

Reputation: 773

The easiest way to achieve desired effect is to have Array of Classes, not Strings. The best way would be, as Nambew wrote, to have Factory.

Upvotes: 0

Related Questions