开发者

Error #1009 with removeChild on Event.target

开发者 https://www.devze.com 2023-04-10 10:34 出处:网络
private function bubbleFlury() { for (var i = 0; i < fluryAmount; i++) { fluryBubble = this.addChild(new bubble());
private function bubbleFlury()
    {
        for (var i = 0; i < fluryAmount; i++)
        {
            fluryBubble = this.addChild(new bubble());
            fluryBubble.addEventListener(Event.ENTER_FRAME, fluryDisplace);
            fluryBubble.yspeed = randomRange(5, 10);

            with (fluryBubble)
            {
                x = Math.random() * sWi开发者_StackOverflow中文版dth;
                y = randomRange(sHeight, (sHeight+sHeight));
                width = height = 1 + Math.random() * 60;
            }
        }

        function fluryDisplace(e:Event):void
        {
            e.target.y -=  e.target.yspeed;

            if (e.target.y <= 0 - e.target.height)
            {
                var t:DisplayObject = DisplayObject(e.target);
                t.parent.removeChild(t)
            }
        }
    }

This is the function I can't figure out:

function fluryDisplace(e:Event):void
    {
        e.target.y -=  e.target.yspeed;

        if (e.target.y <= 0 - e.target.height)
        {
            var t:DisplayObject = DisplayObject(e.target);
            t.parent.removeChild(t)
        }
    }

This throws

Error #1009: Cannot access a property or method of a null object reference.

I'm so confused for some reason.


When you do the removeChild(), make sure to also remove the EnterFrame Event listener:

function fluryDisplace(e:Event):void
{
    e.target.y -=  e.target.yspeed;

    if (e.target.y <= 0 - e.target.height)
    {
        e.target.removeEventListener(Event.ENTER_FRAME, fluryDisplace);

        var t:DisplayObject = DisplayObject(e.target);
        t.parent.removeChild(t);

    }
}

Otherwise, the event keeps firing on and on but the DisplayObject doesn't have a parent anymore and thus t.parent is null (and you get the feared 1009 Error).

Hope my explanation wasn't too confusing. Also, I advice to read carefully what Mattias writes in his comment and try not to add more than ONE EnterFrame listener, as they are very costly performance wise.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号