Forums

ForumsProgramming Forum

removeChild wierd issue

Posted Jan 19, '12 at 8:12pm

TheChicken

TheChicken

2 posts

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

 

Posted Jan 20, '12 at 1:05am

Freckls627

Freckls627

33 posts

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.

 

Posted Jan 20, '12 at 4:41pm

BlueJayy

BlueJayy

27 posts

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.

 

Posted Jan 21, '12 at 2:07am

Nolander777

Nolander777

1 post

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

 

Posted Feb 13, '12 at 1:01am

TheChicken

TheChicken

2 posts

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

 
Reply to removeChild wierd issue

You must be logged in to post a reply!