Creating clones from a DisplayObject instance

Hi,
I am trying to create clones of a give item by using Type.getClass to instance items of the same classtype by Type.createInstance, but I get empty instances as result.

If I use a Bitmap I obtain an empty Bitmap.

Type.createInstance(Type.getClass(particle), []) -> [Object Bitmap] with width and height = 0

If I use a Sprite with a Bitmap inside I obtain a Sprite with an empty Bitmap inside.

It looks like I am losing the Bitmap content in the passage… !!!

So particle is a Bitmap, right? That means that Type.getClass(particle) returns Bitmap, and your code is equivalent to this:

Type.createInstance(Bitmap, []);

Well, what createInstance() does is call the constructor, and it passes the arguments in that array you gave to it. So your code can be simplified even further:

new Bitmap();

Now look at the Bitmap constructor. All of the arguments are optional, so new Bitmap() is completely valid. But if you skip the bitmapData argument, then the bitmap will be empty (at least until you set bitmap.bitmapData = something).

In short, Type.getClass() is not enough to get all the information about an object. Nor is there a workaround for this, as far as I know.


If you know you’re making clones of bitmaps:

var newParticle:Bitmap = new Bitmap(particle.bitmapData);

If you need a way to handle multiple types of object:

public function clone(object:Dynamic):Dynamic {
    if(Std.is(object, Bitmap)) {
        return new Bitmap((cast object:Bitmap).bitmapData);
    } else if(Std.is(object, Shape)) {
        var shape:Shape = new Shape();
        shape.graphics.copyFrom((cast object:Shape).graphics);
        return shape;
    } else {
        //And so on.
    }
}

That isn’t normal at all. The whole point of a clone() function is to make a copy

@player_03: oh yes! Now it is clear! I was instancing a new Bitmap, not the specific Bitmap personalized with a BitmapData! And it works the same if I have a Sprite! Thank you p03!