AS3: Adding function to population loop

Multi tool use
Multi tool use


AS3: Adding function to population loop



Basically I have 2 movieclip objects with some code, currently just to trace them. The blue circles when clicked will say 'Blue' and the red ones when clicked will say 'Red'. This works fine in theory until I add a population loop, which adds more of them. Then only 1 of each colour correctly works, the rest are just 'mock' circles. I wish for each circle to tell me their colour.



This is my code for the .fla:


import flash.events.MouseEvent;
BlueBall.addEventListener(MouseEvent.CLICK, fun1)

function fun1(e:MouseEvent){
trace("Blue!");
}
RedBall.addEventListener(MouseEvent.CLICK, fun2)

function fun2(e:MouseEvent){
trace("Red!");
}



and this is the population loop in an .as file:


private function PopulateCircles():void
{
for (var i:int=0; i < 10; i++)
{
var blueCircle:BlueCircle = new BlueCircle();
this.addChild(blueCircle);

var redCircle:RedCircle = new RedCircle();
this.addChild(redCircle);
}
}



tldr; how do I get the on-click events to occur on every newly populated circle?




1 Answer
1



Pretty easy, actually. Just as you subscribe method to listen the predesigned instances' events, you can subscribe via temporary variable references. As long, as the variable holds the reference (or a pointer in C++ terms), you can address the instance and do anything you could do to a predesigned MovieClip:


private function PopulateCircles():void
{
var aRed:RedCircle;
var aBlu:BlueCircle;

for (var i:int = 0; i < 10; i++)
{
// If there are no mandatory constructor arguments,
// you can omit the () brackets.
aRed = new RedCircle;
aBlu = new BlueCircle;

// Disperse clips to random places.
aBlu.x = 500 * Math.random();
aBlu.y = 500 * Math.random();
aRed.x = 500 * Math.random();
aRed.y = 500 * Math.random();

// Subscribe methods to newly created instances.
aRed.addEventListener(MouseEvent.CLICK, fun2);
aBlu.addEventListener(MouseEvent.CLICK, fun1);

// You're operating inside 'this' object,
// no need to explicitly point it out.
addChild(aRed);
addChild(aBlu);
}
}





Perfect! Sorry for the late response, this tweak was exactly what I needed to help me along. Thank you @Organis
– Sn0wy0wl
Jul 2 at 15:53






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

j6NKjNdFXcbuj UE2yMAdFmT2g6JMR3m8
xamraV7jyaLSgSc,ed 9Ssx 4q51LBiLvpvd,Fm0peFAKWtfzuF5leDvDl7NBdeV3SMo1uGsT EnEjm2VKZr148vV

Popular posts from this blog

Rothschild family

Cinema of Italy