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.
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.
Have a look at flash.utils.getDefinitionByName() or loaderInfo.applicationDomain.getDefinition(), if the assets are ready/loaded.
e.g.
import flash.utils.getDefinitionByName;
var Image:Class = getDefinitionByName(msgObj.image) as Class;
this.addChild(new Image());
HTH
In FlashDevelop 4.0.1 (not sure about older versions), right click on the .swf file. Right below the option to 'Add To Library' is 'Options'. Instead of 'Library (included referenced classes)' select 'Included Library (include completely)'.
It appears that with the first option, when calling the class directly like new BackgroundImage();
the Class is referenced so it gets included. When the calling the class with var backgroundImage:Class = getDefinitionByName("BackgroundImage") as Class;
it's not referenced directly so doesn't get included.
By selecting the second option, all of the classes in the .swc get included and the getDefinitionByName()
then works.
精彩评论