actionscript 3 - Trying to remove object throws error 1009 cannot access a property or method of null object reference -


working on flash game, in previous game had enemies come in using array , when killed or moved off stage remove them array. reason when use same code in game, throws 1009: error when try remove array object, saying there's nothing there. . . strange.

here's code:

public function addzombie() {     var zom:zombie = new zombie();     zom.y = 20;     zom.x = math.floor(math.random()*(1 + 500 - 30)) + 30;     addchild(zom);     zombies.push(zom);     numzombies++; } 

that's function it's added in, zombies array , it's pushed array in function. here's code i'm attempting remove it:

for (var i:int = 0; < zombies.length; i++) {     if (zombies[i].y + zombies[i].height / 2 > 400) {         removechild(zombies[i]);         zombies.splice(i,1);         numzombies--;         addzombie();     } } 

removechild(zombies[i]); <-- part throws error when attempts remove it. removes of them strangely enough, not of them.

i don't believe loop doing quite expect to. when remove element array in way, elements after removed elements moved down. so, if have code like:

var testarr:array = new array(); testarr.push('first'); testarr.push('second'); testarr.push('third'); testarr.push('fourth');  (var i:int = 0; < testarr.length; i++) {     testarr.splice(i,1); } 

the results of loop be:

i=0, testarr = ['second', 'third', 'fourth'] i=1, testarr = ['second', 'fourth'] i=2 end of loop 

it better use while loop, incrementing index if element not removed (since removing element moves new element index position).

i don't see why you're getting null object reference, causing other problems (why removed not all).


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -