Friday, July 22, 2011

Separate class for assets

In projects with many assets it is very handy to embed them in one (or few, but in the same package) class, so you can instantiate them everywhere in the project. The benefit of this is quite obvious - after making any change in your assets you just have to change one class, you don't have to search through the code to find place that is needed to be changed. Assume that
you have one image called image.jpg (not very original , I know) placed in asset.image package. Now you need to create class in asset package called AssetImage (or just Asset, or Resources, or WhateverYouLike):

public class AssetImage
{
  [Embed(source="image/image.jpg")] public static const MY_IMAGE:Class;
}

Now somewhere in your code, where you have a need to instantiate your image, you just need to write:

var myImage:Bitmap = new AssetImage.MY_IMAGE();

After compiling it some Flash-Magic happens and in myImage variable you have your image from image.jpg file. It is very useful when you need to instantiate one asset in many classes in your project - now you don't have to embed this asset in every class. There is also an option to store all of your assets in separate SWF file, but this is another story...

No comments:

Post a Comment