views:

36

answers:

4

Below is a sample:

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

Loads only level1 class, now I dont want to create another function just to load another level..

I want that loadLevel to load level1,level2 etc.. on the same function.

ideas would help. :)

thanks!

+2  A: 
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");
}

another solution might look like this:

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();  
}
maxmc
A: 
 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();              
 }

If your class requires a class path.

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

This is what I use:

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

and call it using:

loadLevel(new Level1());

And make sure that all levels extends from the class Level

class Level1 extends Level

But I think the others solutions work better for a classes like Level1, Level2, Level3. I use this to control scenes in my game, Scene_Title, Scene_Game, Scene_Credits

M28
could be a possibility :) thanks! I am also using "class Level1 extends Level"
keithics
A: 

Here's another answer:

Keep your levels in an array.

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

And then:

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