Monday, October 12, 2009

Calling library objects from a loaded SWF

Herd It is a Flash application that loads lots of external SWFs - to play minigames, show results, etc. - into the main SWF loaded by the player. The problem is that, any object that is defined in the loaded, external SWF is not known to the main SWF in advance and so can not be referenced by the main SWF's ActionScript code.

When you load the external SWF as a Loader, you can refer to objects on it's stage using:
var myLoader:Loader = new Loader();
var myUrlReq:URLRequest = new URLRequest("data.swf");
myLoader.load(myUrlReq);
var myObject:* = myLoader.content["myTimelineObject"];

I always had thought that you couldn't access anything from the external SWF's library - until now! Thanks to this blog post by Koen De Weggheleire (another good thing to come from Belgium), I have learned that it IS possible to access the external SWF's library.
First, we load the loader:
var myLoader:Loader = new Loader();
var myUrlReq:URLRequest = new URLRequest("data.swf");
myLoader.load(myUrlReq);

Once the loader has loaded (you may want an Event.COMPLETE handler to wait for this), we can now find objects in the external SWF's library using the contentLoaderInfo's applicationDomain:
var LibraryClass:Class = loader.contentLoaderInfo.applicationDomain.getDefinition("LibraryClassName") as Class;
var myLibraryObject:MovieClip = new LibraryClass as MovieClip;

Nice one, Belgium!

No comments: