11 March 2011
Load multiple images in AS3 by storing loader information in an object
It’s easy to store images in an array, and loop through that array to access those images. The code is very clean, and easy to manage. My concept is to try and load images from an array by looping through the array, and reusing one loader method multiple times. I would instantiate a new loader instance each iteration through the loop, and then load the image. The problem, however, is by the time the image is actually loaded, the for loop is complete, and my call addChild(l) is referring to the last time Loader was instantiated, so all of the images loaded were the last one in the array.
I’ve found an elegant solution to this (in my opinion) by creating an object for each image, and to store information about the image in that object, including an instance of the loader. Let me show you.
Example
//counter to keep track of unique items in the array
var counter:Number = 0;
//base array with paths to the images
var images:Array = ["img1.jpg", "img2.jpg", "img3.jpg", "img4.jpg"];
//blank array which will be filled with objects that contain image data
var imageObjectArray = [];
for(var i:uint = 0; i < images.length; i++) {
//create blank object with appropriate properties
var imgMeta:Object = {imgPath: null, holder:null, loaderInst: null};
//push the object into imageObjectArray so we can access it later
imgObjectArray.push(imgMeta);
//set the properties we know
imgMeta.imgPath = images[i];
var imgHolder:Sprite = new Sprite();
imgMeta.holder = imgHolder;
//load the image here
var l:loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, onDoneLoading);
l.load(new URLRequest(imgMeta.imgPath));
}
//function called when each image is done loading
function onLoadComplete(e:Event) {
//use counter here to make sure we're getting the correct imageObject
//we need to call each unique loaderInst here, so each image is unique
addChild(imgObjectArray[counter].loaderInst);
counter++;
}
This of course can be classed out and abstracted, but the basic principal here is being able to reuse the loader code each time through the for loop, and displaying each unique image when it’s done being loaded.
An additional benefit to this is being able to use the object again anywhere in your code, since all the information for all of the images is stored in imgObjectArray.

