Reputation: 455
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
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
Reputation: 18546
var balls:uint = 0;
for(var i:uint=0,l:uint = numChildren; i<l;i++)
if(getChildAt(i) is Ball) balls++;
var balls:uint = 0;
function addBall():DisplayObject {
balls++;
return addChild(new Ball());
}
function removeBall(ball:Ball):DisplayObject {
balls--;
return removeChild(ball);
}
var ballContainer:Sprite = new Sprite();
addChild(ballContainer);
...
ballContainer.addChild(new Ball());
var balls:uint = ballContainer.numChildren;
Upvotes: 2
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