Search code examples
actionscript-3clone

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...?


Solution

  • 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.