Search code examples
imageflashtranscode

Flash embedding image from string parameter


I'm trying to embed an image in the constructor of my RangedItem class

public class RangedItem extends Item{

    public var speed:Number;
    public function RangedItem(s:Number, n:String, d:Number, path:String):void{
        super(n, d);
        speed = s;
        [Embed(source=path, mimeType="image/png")] const IMAGE:Class;
    }
}

Here is the code i'm using to construct the item

items.push(new RangedItem(item.speed, item.name, item.damage, '/img/gun.png'));

But I get these errors

col: 4: Error: unable to resolve 'path' for transcoding
col: 4: Error: Unable to transcode path.

img/gun.png exists for sure because if I replace path with "img/gun.png" everything works fine.

I'm using the flashpunk framework by the way if that changes anything.
What am I doing wrong? Thanks in advance!


Solution

  • The [Embed] metadata, is used at compile time, not run time. So the variable interpolation that you're trying to do here with path won't work:

    [Embed(source=path, mimeType="image/png")] const IMAGE:Class;
    

    The compiler is expecting a literal string with the path to the image:

    [Embed(source="path/to/my/image.png", mimeType="image/png")] const IMAGE:Class;
    

    What you might consider doing is creating a Singleton (or your favorite pattern) class that contains all of your embedded images. Then your classes can refer to the assets in the singleton class and even pass references to them in the constructors of other classes.