AS3中的动态类?

时间:2010-08-26 21:23:55

标签: actionscript-3

以下是一个示例:

    private function loadLevel(name:String):void{
        level1 = new Level1(name);      
        level1.onInitialize.addOnce(onLevelReady);
        level1.loadData();              
    }

仅加载level1类,现在我不想再创建另一个函数来加载另一个级别..

我希望loadLevel在同一个函数上加载level1,level2等。

想法会有所帮助。 :)

谢谢!

4 个答案:

答案 0 :(得分:2)

private function loadLevel(level : int, name : String) : void {
    try {
        var LevelClass : Class = getDefinitionByName("Level" + level) as Class;
        // i think you should also create an ILevel interface for your levels
        var level : ILevel = new LevelClass(name) as ILevel;
        level.onInitialize.addOnce(onLevelReady);
        level.loadData();  

    } catch(e:Error) {
        trace("Failed: " + e.message)      
    }
}


private function somewhere() : void {
   // The downside is that you need to make sure the actual Level1,Level2,... classes 
   // are included by mxmlc when compiling your swf. This can be done by refencing them somewhere in the code.
   Level1;
   loadLevel(1, "some Level");
}

另一个解决方案可能如下所示:

private function loadLevel(level : int, name : String) : void {
    var level : ILevel;
    switch(level) {
        case 1:
            level = new Level1(name);
            break;
        case 2:
            level = new Level2(name);
            break;
        default:
            throw new Error("No such Level");
    }

    level.onInitialize.addOnce(onLevelReady);
    level.loadData();  
}

答案 1 :(得分:0)

 private function loadLevel(name:String, level:Number):void{
     var Level:Class = getDefinitionByName("Level" + level) as Class;
     level1 = new Level(name);      
     level1.onInitialize.addOnce(onLevelReady);
     level1.loadData();              
 }

如果您的班级需要课程路径。

var Level:Class = getDefinitionByName("com.domain.Level" + level) as Class;

答案 2 :(得分:0)

这就是我使用的:

private function loadLevel(level:Level):void{      
    level.onInitialize.addOnce(onLevelReady);
    level.loadData();              
}

并使用:

调用它
loadLevel(new Level1());

确保所有级别都从类Level

延伸
class Level1 extends Level

但我认为其他解决方案对于Level1,Level2,Level3等类更有效。我用它来控制游戏中的场景,Scene_Title,Scene_Game,Scene_Credits

答案 3 :(得分:0)

这是另一个答案:

将您的关卡保持在阵列中。

private const levels = [null, Level1, Level2, Level3]

然后:

private function loadLevel(name:String, n:int):void{
    level = new (levels[n])(name);      
    level.onInitialize.addOnce(onLevelReady);
    level.loadData();              
}