Access / load library assets from another SWF in Flash CS3
23 August , 2007Posted by on
In this short article I would like to focus on a simple technique to load library assets from another SWF which is actually used as class container. I already used that technique several times and it comes in handy in some situations. In my opinion it is especially handy when you are working on a project with several people and one is doing the design of the assets to be used. It also can be handy when it comes to streamlined preloading of several assets. We use one SWF then as dataContainer for all the assets, the base swf loads the dataSWF and from then on the assets are accessible and can be instantiated.
Let’s illustrate the technique using a simple example:
Imagine we have one simple SWF (eg : data.swf) that contains one library item: a movieclip with a designed little square with a class name Square that uses Movieclip as his base class. As you know, in Flash CS3 a class is automatically generated when you not specify a custom class so in our SWF we can normally instantiate a Square object by writing this code:
var mySquare:Square = new Square();
But imagine that we have another SWF (eg: base.swf) where we would like to instantiate also Square objects. Thats were the technique of dynamic class loading comes in. First thing we have to do is to load the “data.swf” inside the base.swf like this:
var myLoader:Loader = new Loader();
var myUrlReq:URLRequest = new URLRequest(“data.swf”);
As you can see we call the onLoaded function when the data.swf is fully loaded. The onLoaded function is the place where we are going to access the SWF his contents, in our case the Square in the library. The final onLoaded function looks like this:
var Square:Class = event.target.applicationDomain.getDefinition(“Square”) as Class
var mySquare:MovieClip = new Square() as MovieClip;
As you see we first instantiate a class object and we acces the Square class (inside the library of the data.swf) and cast it as a Class also. From then on you can instantiate as much squares you want. To avoid flash saying that a square datatype isn’t found we cast a new Square object immediately to a MovieClip where it is extending from. The last thing we do is adding the square to the displayList by calling the addChild method.
Very simple technique but comes in handy in some situations 😉