redconservatory
redconservatory

Reputation: 21924

Clone an instance of a class (Display Object)

I have a collection of movieclips, I would like to create a clone (a new instance) of a instance everytime I create a new object.

For example

var s:Star = new Star(); // star-shaped movielcip
addChild(s);
// then I want to duplicate an instance of s and add it beside s

For an example like above, it's simple enough to create a new instance with a different name and just add it to the display list. But I have a list of objects I would like to clone as a group...?

Upvotes: 0

Views: 2998

Answers (2)

HotN
HotN

Reputation: 4386

moses' solution is correct. What is the purpose of the clone, where you wouldn't need to know the name of the clone to reference it?

One option is you could create an array to store your references in so you don't need to explicitly name them. Using moses' code...

var clones:Array = new Array();
for each (var star:Star in [s, s2, s3, s4, s5]) {
    clones.push(clone(star));
}
trace(clones.length);   // 5

This will result in an array that holds 5 cloned stars. It takes the least amount of code but it's up to you to make sure you know which star is which afterwards.

Upvotes: 1

miqbal
miqbal

Reputation: 2227

Belowed code is very famous for cloning the objects. It's deepest and dynamic.

...
    function clone(orjObj:Object):Object {
        var copyObj:ByteArray = new ByteArray();
        copyObj.writeObject(orjObj);
        copyObj.position = 0;
        return(copyObj.readObject());
    }

    var s2:Star = clone(s);
    s2.x = s.x + s.width;
    s2.y = s.y;
    addChild(s2);

Upvotes: 2

Related Questions