AS3 删除对象的所有实例



我在 AS3 中有一个游戏,其中包含一个文档类和一个附加到我.fla中的电影剪辑的自定义类。该对象的实例每秒多次创建。我想删除这些实例,假设有 100 个实例。(因为一段时间后出现性能问题)实例在创建后存储在数组中。

您可以使用

this.removeChild(obj);删除它们,obj 是数组中的对象。因此,您需要的是遍历数组并删除它们。

当对象超过 100 时,这将删除所有对象。

if(array.length > 100)
{
  for(var i:int = array.length - 1; i > -1; i--)
  {
    stage.removeChild(array[i]);// or any other parent containing instances
    array.pop();
    //array[i] = null; // if you want to make them null instead of deleting from array
  }
}

提示:负循环 (i--) 的性能比正循环 (i++) 快。
提示:pop() 在性能上比 unshift() 更快。

更新

仅当对象超过 100 个时,才会删除对象,从而导致舞台上仅保留 100 个最后对象。

if(array.length > 100)
{
  for(var i:int = array.length - 1; i > -1; i--)
  {
    if(array.length > 100)
    {
      stage.removeChild(array[i]);// or any other parent containing instances
      array.unshift();// if you want to delete oldest objects, you must use unshift(), instead of pop(), which deletes newer objects
      //array[i] = null; // if you want to make them null instead of deleting from array
    }
}
/****** MyClass.as  *********/
public class MyClass extends Sprite{
    private var myVar:int=8567;
    private function myClass():void{
        //blablabla
    }
    public class destroy():void{
        myVar = null;
     this.removeFromParent(true); //method of Starling framework
    }
}

/********  Main.as  ****************/
public var myInstance:MyClass = new Myclass();
//Oh!! i need remove this instance D:
myInstance.destroy();

最新更新