I've been trying to create an universal asset loader class (with help of the folks here at stackoverflow), which remembers previousely downloaded assets by storing them in an associative array.
This is the end result:
AssetLoader.as
package
{
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.utils.ByteArray;
public final class AssetLoader extends Loader
{
public static var storedAssets:Object = {};
private var postUrl:String;
private var urlRequest:URLRequest;
private var cached:Boolean = false;
public final function AssetLoader(postUrl:String):void
{
this.postUrl = postUrl;
if (storedAssets[postUrl])
{
cached = true;
}
else
{
urlRequest = new URLRequest(Settings.ASSETS_PRE_URL + postUrl);
contentLoaderInfo.addEventListener(Event.COMPLETE, OnAssetLoadComplete);
}
}
//starts loading the asset
public final function loadAsset():void
{
if (cached)
{
loadBytes(storedAssets[postUrl]);
}
else
{
load(urlRequest);
}
}
//runs when the asset download has been completed
private final function OnAssetLoadComplete(event:Event):void
{
storedAssets[postUrl] = contentLoaderInfo.bytes;
}
}
}
Settings.ASSETS_PRE_URL equals "http://site.com/assets/"
Now, my problem is that it is causing the client to crash whenever it tries to retrieve the caches version (the newly downloaded one does work) from the class:
var assetLdr:AssetLoader = new AssetLoader("ships/" + graphicId + ".gif");
assetLdr.contentLoaderInfo.addEventListener(Event.COMPLETE, onShipAssetComplete);
assetLdr.loadAsset();
private function onShipAssetComplete(event:Event):void
{
var shipImage:Bitmap = Bitmap(event.target.loader.content);
// Do stuff with shipImage
}
When the cached version is being loaded, I get the following error in dutch: "TypeError: Error #1034: Afgedwongen typeomzetting is mislukt: kan flash.display::MovieClip@5c13421 niet omzetten in flash.display.Bitmap. at GameShip/onShipAssetComplete()" - means something like "type convertion has failed, can not convert flash.display::MovieClip@... to flash.display.Bitmap".
So, I wonder, how should I extend this loader class and make it return a cached asset the right way? Is my way of storing the asset in the array invalid maybe? Or should I use something else than loadBytes in the AssetLoader method?