Search code examples
xmlflashactionscript-3swc

Flash AS3 Attach SWC Symbol Based on XML Element


I have a SWC which contains 8 sprites, each of which has a linkage identifier with the pattern Icon01, Icon02, etc. I can create an instance of one of these sprites by doing something of the form

var i:Icon01 = new Icon01();
this.addChild(i);

However, I have an XML file which contains different messages, and each message contains an image element that is labeled in the same fashion

...
<message>
    <image>Icon01</image>
</message>
...

I would like to be able to parse the XML and have the corresponding sprite attached to the stage. How can this be done?

My XML data is parsed into an array of objects and the XML element lives in

var msgObj:Object = this.theMessages.messages.shift();
trace(msgObj.image);

But I can't figure out how to cast it as a sprite and add it to the stage. I tried doing

var s:Sprite = msgObj.image as Sprite;
this.addChild(s);

And I just get an error about a NULL object. Thanks for any help.


Solution

  • getDefinitionByName(msgObj.image) would be the way to go, but you will need to reference each class you might be calling somewhere otherwise it won't get compiled.

    what I do in this case is create a dummy function that never gets called and list all the classes there, that way you force the compiler to include it.

    Another option is to load these using the [embed] feature instead of using the swc, that way you are guaranteed that they are compiled and can be called at any time.