Cloning/Copying Objects in AS3

I was recently working on a game that was controlled mostly by arrays (it was a puzzle game). When a user would fail a level I would have to reset the pieces to be back to how they were at the start of a level.

Setting up a function to reset the level just didn’t make sense. I wasn’t completely sure how I could get this done properly. I tried to create a second value that would remain constant in my code that mirrored the original look of the level’s unfinished puzzle and when the user would fail I would just overwrite the current state of the level with the constant version of that level. Obviously due to referencing in flash this didn’t work.

I learned about a function in Flex known as “copy” in the ObjectUtil class that would clone a data object, just as I was trying to do. Linking the Flex classes into the project didn’t make sense for me, so I needed to recreate the function for AS3. I thought it would be difficult but I was able to get some help and ended up with the following:

function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}

It worked perfectly. I can now copy objects extremely easy in Flash with this clone function. I hope that it will help anyone out there who may need a solution for a similar problem.

Tags: , , ,

Leave a Reply

Or enter details below...