Zeeshan Ahmad
Zeeshan Ahmad

Reputation: 455

counting the number of instances of a particular class on stage in as3

Does some one know how to get the number of instances of a particular class (in my case Ball.as) currently on the stage.

Note: I want a solution to not include the use of numChildren and then looping through all children, as I want the number of Balls every enterFrame and looping like that might just make my code more heavier.

So any suggestions?

Upvotes: 1

Views: 1654

Answers (3)

Pixel Elephant
Pixel Elephant

Reputation: 21383

You can use a static variable within the class to keep track, but that you means you have to correctly keep track at this variable at all times, or it could end up with the wrong count.

public static var count:int = 0;


public Ball() {
   addEventListener(Event.ADDED, onAdded);   
   addEventListener(Event.REMOVED, onRemoved);
}

private function onAdded(event:Event):void {
   removeEventListener(Event.ADDED, onAddeed);
   Ball.count++;
}

private function onRemoved(event:Event):void{
   removeEventListener(Event.REMOVED, onRemoved);
   Ball.count--;
}

and then whenever you want to count them:

trace(Ball.count);

Upvotes: 2

J. Holmes
J. Holmes

Reputation: 18546

a) Count them

var balls:uint = 0;
for(var i:uint=0,l:uint = numChildren; i<l;i++)
  if(getChildAt(i) is Ball) balls++;

b) Keep track of them

var balls:uint = 0;

function addBall():DisplayObject {
   balls++;
   return addChild(new Ball());
}

function removeBall(ball:Ball):DisplayObject {
   balls--;
   return removeChild(ball);
}

c) Isolate them

var ballContainer:Sprite = new Sprite();
addChild(ballContainer);

...

ballContainer.addChild(new Ball());

var balls:uint = ballContainer.numChildren; 

Upvotes: 2

locrizak
locrizak

Reputation: 12281

I don't think there would be a way to get around doing the loop.

When I have an Actionscript project of any size I will create a static Manager class that will handle all app wide variables. You could create an Array in there and add/remove from that when a new instance of ball is created.

Upvotes: 1

Related Questions