简体   繁体   English

在as3中计算舞台上特定类的实例数

[英]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. 是否有人知道如何获取舞台上当前特定类(在我的情况下为Ball.as)的实例数量。

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. 注意:我希望一个解决方案不包括使用numChildren,然后循环遍历所有子项,因为我希望每个enterFrame和这样的循环的球数可能会使我的代码更重。

So any suggestions? 有什么建议吗?

a) Count them a)数一下

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 b)跟踪他们

var balls:uint = 0;

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

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

c) Isolate them c)隔离它们

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

...

ballContainer.addChild(new Ball());

var balls:uint = ballContainer.numChildren; 

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);

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. 当我有一个任意大小的Actionscript项目时,我将创建一个静态Manager类,该类将处理所有应用程序范围的变量。 You could create an Array in there and add/remove from that when a new instance of ball is created. 您可以在其中创建一个数组,并在创建新的ball实例时从中添加/删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM