ForumsProgramming ForumremoveChild wierd issue

4 3904
TheChicken
offline
TheChicken
2 posts
Nomad

Trying to remove multiple of children of a displayObject of type Button

for (var i:int=0; i<numChildren; i++) {
if (getChildAt(i) is Button) {
removeChild(getChildAt(i));
}
}
for (var h:int=0; h<numChildren; h++) {
if (getChildAt(h) is Button) {
trace("???????&quot;
}
}
During gameplay, it traces out "???????", and I'm not quite sure why

  • 4 Replies
Freckls627
offline
Freckls627
31 posts
Nomad

I believe getChildAt() refers to a layer and not an index of the children. Try doing a for each statment where tempvar:displayobject is Button.

BlueJayy
offline
BlueJayy
27 posts
Nomad

When you remove a child, it shifts everything down one layer, so you're actually only removing about half of the children. In your first if statement, add another line that says "i--" which will shift your i back one layer to compensate for the removed child. I believe that should work.

Nolander777
offline
Nolander777
1 posts
Nomad

BlueJayy is right, numChildren decrements with every removal. But I would suggest a simpler approach of just iterating backwards:

for(i = numChildren-1;i>=0;i--)

This way, only indexes that have already been checked can shift. (e.g. if you start with numChildren = 7 (indexes 0,1,2,3,4,5,6), and you iterate backwards, finding your first Button at index 4, removing that once will shift index 5 and 6 down, but your next check at index 3 will not have changed.)

TheChicken
offline
TheChicken
2 posts
Nomad

Haha oops.... I forgot this was a mutable array, I'm used to java in school with arrays vs arraylists so I got them mixed up. Thx alot

Showing 1-4 of 4