views:

904

answers:

2

How can you add data to a dynamically created MovieClip/Sprite so that the data can be accessed later on an event coordinating to that MovieClip/Sprite?

Example Code:

for(var i:int; i < xml.children(); i++){
    var button:MovieClip = new MovieClip();
    button.graphics.beginFill(0x000000);
    button.graphics.drawCircle(100 + 20 * i, 200, 10);
    button.graphics.endFill();
    button.addEventListener(MouseEvent.MOUSE_UP, doSomething);
    button.name = "item_"+i;
    button.storedData.itemNumber = i;
}

function doSomething(e:Event):void
{
    trace(e.target.storedData.itemNumber);
}

Thanks in advance.

+4  A: 

Luckily for you, in AS3, the MovieClip class is defined as a dynamic class (and only movie clips are, sprites not). In a class that has been defined as dynamic, you can add a new dynamic instance to any instance of that class via a standard variable assignment statement.

var myInstance:DynamicClass= new DynamicClass();
myInstance.foo = "hello World"; // this won't cause any compile time errors

trace(myInstance.foo ); //returns hello World

EA-SY ^_^

Exemple

Now let's create dynamically several MovieClips and then change a property of one of them.

AS2 syntax:

for(var i:Number = 0; i < 10; i++){
    _root.createEmptyMovieClip("button" + i, _root.getNextHighestDepth());
}

Then you could call your movie clip directly :

button3._x = 100;
button3._y = 300;

or dynamically by using this :

this["button" + i]._x = 100;
this["button" + i]._y = 300;

In AS3, it is quite different (and there would be many ways to do it).

AS3 syntax:

var button:Array = new Array();

for (var i:Number = 0; i < 10; i++) {
    var _mc:MovieClip = new MovieClip();
    addChild(_mc); // in AS3 when you create a MovieClip, it remains in memory and won't be seen on stage until you call addChild(_mc)

    button[i] = _mc;
}

Then you can have some fun with your movie clips, dynamically :

button[2].graphics.beginFill(0x000000);
button[2].graphics.drawCircle(100, 200, 10);
button[2].graphics.endFill();
Blackethylene
Awesome, so how would I create a dynamic button name in a for loop then like button1, button2, button3, etc. using:var button:MovieClip = new MovieClip();
Torez
I updated my answer
Blackethylene
A: 

So great! This is exactly what I was looking for! Thanks so much! I spent many hours trying to figure this one out.

Cervelo Man