I have a game with in AS3 with a document class and a custom class which is attached to a movieclip in my .fla. Instances of that object are made multiple times/second. I want to delete those instances when, let's say, there are 100 of them. (because of performance problems after a while) The instances are stored in an Array after they are made.
Asked
Active
Viewed 2,120 times
0
-
So what's the problem, you have a reference to all of them in an array, you have some container (assuming they're Sprites/MovieClips/DisplayObjects/UIComponents of some sort) when the array.length is greater than 100 start unshifting the items from the beginning of the list and remove them from the container, you can re-use/recycle these instances or let them be garbage collected (re-use is better remember, reduce, re-use, recycle). myArray.unshift() pulls the first item from the list (acting like a queue, FIFO first in first out) – shaunhusain May 28 '12 at 19:59
3 Answers
0
You can remove them by using this.removeChild(obj);
and obj is your object from array. So what you need is to loop through array and remove them.

Senad Meškin
- 13,597
- 4
- 37
- 55
0
That will remove all objects when objects are over 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
}
}
Tip: Negative Loop (i--) is faster in performance than Positive Loop (i++).
Tip: pop() is faster in performance than unshift().
Update:
That will remove objects only if they are over 100, resulting in only 100 last objects remain on stage.
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
}
}

vozochris
- 68
- 1
- 8
-
is this better performance wise than unshift? also I would assume you don't want to actually empty the entire collection but rather remove the oldest references. – shaunhusain May 28 '12 at 21:42
0
/****** 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();