0

I have a list of objects and I'm attempting to iterate through the list and check for a collision, at which point a motion tween will play at the end of which the function to remove the object will be executed.

stage.addEventListener(Event.ENTER_FRAME, hitTest);
function hitTest(e:Event ):void
{
    for each (bullet in bullets)
    {
        if (bullet.parent == null)
        {
            bullets.splice(bullets.indexOf(bullet),1);
        }
        else if (bullet.hitTestObject(shark))
        {
            trace("HIT1");
            bullet.gotoAndPlay(2); //part that's giving me trouble
            bullets.splice(bullets.indexOf(bullet),1);
            trace("HIT");
        }
        else
        {
            for each (enemy in enemies)
            {
                if (enemy !=null && bullet.hitTestObject(enemy))
                {
                    enemies.splice(enemies.indexOf(enemy),1);
                    enemy.remove();
                    enemy = null;
                    bullets.splice(bullets.indexOf(bullet),1);
                    bullet.remove();
                    break;
                }
            }
        }
       }

going through list testing various things.

at the end of the motion tween setup for the bullet object of the Bullet class

stop();
this.remove();

this is the remove function in the bullet class

public function remove() {
    parent.removeChild(this);
    this.removeEventListener(Event.ENTER_FRAME, moveMe);
}

specific error

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Bullet/remove()
at Bullet/frame20()

frame 20 is the last frame of the motion tween and has the code above^^

thanks for any help.

1 Answer 1

2

Removing items from an array you are iterating over changes the length of the array and can lead to errors. Options are to iterate over the array backwards or have a local temporary array that you push the indices of your "hits" into and then do the removal from your main array after the main for loop is complete and then iterate over the temps array.

See here and here for similar issues with discussion and solution examples.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.