Save variable in Movieclip or Sprite

How can you add data to dynamically created MovieClip / Sprite so that data can be accessed later in the event coordinated with this MovieClip / Sprite?

Code example:

  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
source share
1 answer

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

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 us dynamically create several clips, and then change the property of one of them.

Syntax AS2:

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

Then you can directly call your clip:

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

or dynamically using this:

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

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

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 enjoy the videos dynamically:

 button[2].graphics.beginFill(0x000000); button[2].graphics.drawCircle(100, 200, 10); button[2].graphics.endFill(); 
+6
source

All Articles