Search code examples
actionscript-3flashevalswcsquare-bracket

Square bracket notation to dynamically load library items?


So I've spent an embarrassing number of hours trying to save myself a few minutes and make my code a bit neater, and Google has produced nothing, so now I come crawling to stackoverflow. The problem is with square bracket notation + library items:

So let's say you have a MovieClip called "myMC_5", and you want to set its X position to 0..

myMC_5.x = 0;

..and if you don't want to hard-code the name of the MC but instead you want one line of code to move a specific MovieClip based on a variable, you could do something like this:

var selectMC = 5;
root["myMC_"+selectMC]x = 0;

..and this will have the exact same effect as myMC_5.x = 0, except that this time you must specify the location ("root" or "this" or something).

THE PROBLEM:

I'm working on a game in which the graphic for the background is loaded from the library, and it's different for each level. The initial loading of the vector from the library looks like this:

private var land:vector_land0 = new vector_land0();

..and this works fine, but it only loads that one specific vector. There should be about 30 or more. I'd like to just have 1 line of code in the constructor to load any of them, based on a variable which keeps track of the current level, like this:

private var land:["vector_land"+theLevel] = new ["vector_land"+theLevel]();

..but that doesn't work. I get syntax errors ("expecting identifier before leftbracket") because you need to specify the location of the object, like in the first example:

root["myMC_"+"whatever"].x = 0;

..but this library item has no "location". So, how the heck do I dynamically load a vector from the library? It's not "on the root", or anywhere else. It has no location. I refuse to believe that the standard method for accomplishing this is to create 30 different classes or write a giant block of code with 30 "if" statements, but searching Google has found nothing. :(


Solution

  • It sounds like you're looking for getDefinitionByName(), which you could use to do something like this:

    import flash.utils.getDefinitionByName;
    
    private var LevelVectorClass:Class = getDefinitionByName("vector_land" + theLevel) as Class;
    private var land:Object = new LevelVectorClass();