1

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?

Michael0x2a
  • 58,192
  • 30
  • 175
  • 224
MKII
  • 892
  • 11
  • 36

3 Answers3

2

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.

ghost23
  • 2,150
  • 1
  • 20
  • 35
  • Uhm... So basically create something like an enumeration, and then use a Character object as a container for the class I need to create, right? However, how would I be able to use the object constructor, if I needed to? Something like unitMap["hero"]( arg ) would work? – MKII Mar 02 '12 at 10:00
  • yes, correct, that would work. By the way, of course, you could also directly reference the classes you want to create. i just thought, it might be helpfull, if the classes you create, all extend a base class or implement an interface for easier usage. That's what i was referring to with "Character". – ghost23 Mar 02 '12 at 14:38
1

If you're looking to dynamically create multiple types of entities that require construction work, try to always use an abstract factory. It will make you game much more flexible and modular. Especially for a strategy game, you might have complex logic that builds each of the units. Check out the below article:

http://www.as3dp.com/2010/11/saturated-abstract-factory-1-wholesale-creation/

Jonathan Dunlap
  • 2,581
  • 3
  • 19
  • 22
  • My time is limited (since this game is a college project) so I probably won't be able to understand and implement the above solution before my deadline, still it seems more than worth a look. Thank you. – MKII Mar 03 '12 at 02:08
1

You may also want to look at the PushButton engine, which will provide some out of the box features to deal with all different games objects. It has Dependency Injection features, which is a good practice to decouple usage and creation of objects.

https://github.com/PushButtonLabs/PushButtonEngine

Antoine Lassauzay
  • 1,557
  • 11
  • 12
  • Like above, this is something I will look in detail as soon as possible. Thank you. – MKII Mar 03 '12 at 02:16