Actionscript: Accessing MovieClips from an externally loaded SWF
For the time I’m working on a website and so far I’ve only spent some time doing research around all the ideas I have. One of them was to put all MovieClips in one externally loaded SWF. Loading the SWF is easy, but how do you access the individual MovieClips? Easy as 1-2-3!
For loading the assets I use BulkLoader; so far it seems like a pretty good alternative to writing a bunch of code myself. I like.
In the assets.swf I have only stuffed the library with MovieClips, and the ones I’d like to access from the outside are set to linked. Nothing is placed on stage. The document root to the SWF is set to a custom class. It is within this class the trick lays. And the trick is to set up a public function that returns any MovieClip to the parent SWF.
The parent SWF loads assets.swf and puts it in a variable. The public function in the assets document class is now accessible by dot syntax. By calling this function we can easily add MovieClips from the assets library to any MovieClip in the parent SWF.
Here’s the document class for assets.swf:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package { import flash.display.MovieClip; import flash.utils.getDefinitionByName; public class Assets extends MovieClip { public function Assets() { } public function getAsset(s:String):* { var a:Class = getDefinitionByName(s) as Class; return new a(); } } } |
What this does is first of all import getDefinitionByName from the flash.utils package. This is a function that will return any object based on the string you give it. Second, and last, is setting up a generic public function that will look for and return an object with the name you provide it with.
In the parent SWF you would set up an eventHandler that puts the loaded SWF in a variable, and then call getAsset(). Like this (note that I’m using BulkLoader):
1 2 3 4 5 6 | private function mclibLoaded(e:Event):void { var lib:MovieClip = loader.getContent("mclib"); var p1:MovieClip = lib.getAsset("Page2"); keeper.addChild(p1); } |
loader is the name of the BulkLoader object, and keeper is a MovieClip on stage.
Rather easy, right?
If you’re interested in knowing more about BulkLoader, take a look at the documentation.
The generic function I’ve written here was taken from Big Spaceship Labs. They did it in a more elegant way than I initially did. Don’t thank me, thank them.