Search code examples
flashactionscriptconstructortheory

Dealing with many objects


I am making a strategy game and came across a kind of problem. Basically, I don't know how to deal with the dynamic creation of the units I need. Should I use some big switch statement or is there a more ideal solution?


Solution

  • I assume, you are essentially talking about instantiating different kinds of classes at runtime. The possibilities are numerous :)

    One option is:

    You manage a map (basically an object), where the key is an identifier of your "unit" and the value is a class object, like so:

    var unitMap:Object = {
        "hero": UserGameCharacter,
        "enemy": NPCharacter,
        "chicken": ChickenCharacter
    };
    

    Note, that the values are class objects, not instances. Furthemore, let's assume, that all the character classes either extend a base Character class or implement a Character interface. Now, when you want to instanciate a "unit", you would do this:

    var newCharacter:Character = new (unitMap["hero"])();
    

    This way, you don't need a switch statement anymore. Hope, this helps as a starting point.