Flash AS3 Attach SWC Symbol Based on XML Element

╄→гoц情女王★ 提交于 2019-12-24 23:37:34

问题


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.


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/5412375/flash-as3-attach-swc-symbol-based-on-xml-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!