Search code examples
arraysactionscript-3sortingz-indexchildren

Loop children while shifting skips


I'm stuck with this code I created. What it does is that it loops through all the children in a class and then checks if it has the priority property set to 1. When the the priority is 1 it gets added to the end of the childList. The problem I am having is that when it finds an object with priority 1 it skips the next object. This is because it moves the object to the end, meaning that the whole array moves one position to the left so it skips the next object because it thinks it already checked it!

for (var j:int = 0; j < this.numChildren; j++) 
    {
        var tempObject:Object = this.getChildAt(j);
        if (tempObject._priority == 1)
        {
            var indexofnew:Number = this.getChildIndex(tempObject as DisplayObject);
            this.setChildIndex(this.getChildAt(indexofnew),this.numChildren-1); 
        } 

I have run into a complete wall on how to solve this. Does anybody have an idea?


Solution

  • The issue is that when you move the position of a given child on the display list to the end of the list, the index of the other children below it will decrement.

    the best approach could be to iterate through the loop backwards as the only changes to the child indexes would be on the DisplayObjects already processed.

    for (var j:int = numChildren-1; J >= 0; j--) 
    {
            var tempObject:Object = this.getChildAt(j);
            if (tempObject._priority == 1)
            {
                var indexofnew:Number = this.getChildIndex(tempObject as DisplayObject);
                this.setChildIndex(this.getChildAt(indexofnew),this.numChildren-1); 
            } 
    }