Search code examples
xmlactionscript-3flashdevelop

Using XML to instantiate a class in AS3


XML File:

<MapDetails>
<MapTiles TileWidth="16" TileHeight="16">TestMap1Tiles</MapTiles>

<MapTileFile>TestMap1</MapTileFile>

<Enemy1Class>SkellMonsta</Enemy1Class>

Super simple. I want to use an xml file to define everything in the map. I have the xml file loaded properly in my GameState class. Everything traces out fine. (Using Flixel, btw).

add(map.loadMap(new TestMap1, TestMap1Tiles, mapXML.MapTiles.@TileWidth, mapXML.MapTiles.@TileHeight));

Could not use mapXML.MapTileFile to reference TestMap1. I get this if I try:

Error #1007: Instantiation attempted on a non-constructor.

Same thing happens if I try to reference the SkellMonsta class like this:

enemies.add(mapXML.Enemy1Class = new mapXML.Enemy1Class(100, 40, hero));

I've tried using - as Enemy - but that doesn't work. What am I missing here?


Solution

  • Your issue is that you are trying to use a string value from your xml like it's a class.

    You first need gain a reference to the actual class. You can do this with flash.utils.getDefinitionByName

    This method will take a string reference and return a Class reference. Keep in mind though, that it wants a fully qualified name, so it should include any packages references. So in other words, flash.display.Sprite instead of Sprite.

    So for your example, assuming your Enemy classes are top level, you could do:

    var cls:Class = getDefinitionByName(getmapXML.Enemy1Class) as Class;
    
    enemies.add(new cls(100, 40, hero));