【问题标题】:Removing an event listener as well as a sprite at the same time AS3同时移除一个事件监听器和一个精灵 AS3
【发布时间】:2011-04-04 19:33:29
【问题描述】:

我无法同时删除事件侦听器和精灵。我目前收到一个错误:

TypeError:错误 #1009:无法访问 空对象的属性或方法 参考。

如果我注释掉 removeChild,我没有错误,但显然,精灵仍然在屏幕上。有什么想法可以让我自己摆脱这个错误吗?

     //Bullet extends Sprite Class
     bullet:Bullet = new Bullet();
     mc.addChild(bullet);
     bullet.addEventListener(Event.ENTER_FRAME, shoot);

     function shoot(e:Event):void {
        var shot:Bullet = e.currentTarget as Bullet;
        //check shot is outside the frame
        if (shot.x < 0 - shot.width || shot.x > stage.stageWidth || shot.y > 525)
        {
            //trying to remove the thing and it's listener
            e.currentTarget.removeEventListener(e.type,arguments.callee);
            e.currentTarget.parent.removeChild(shot);
        }
        else
        {
            shot.setInMotion();
        }
    }

【问题讨论】:

  • 别忘了放入 shot.y
  • 只是一点:通常在添加事件监听器时,使用弱引用,即 addEventListener(Event, shoot, false, 0, true),这允许对组件进行垃圾收集,其行为类似于删除事件监听器

标签: actionscript-3 actionscript event-handling removechild


【解决方案1】:

除了在 bullet:Bullet 之前缺少 var 之外,我在示例代码中看不到任何错误。您应该在之后设置断点:

var shot:Bullet = e.currentTarget as Bullet;

并找出为什么 shot 为空。我怀疑在您作为示例提供的那一点之外的一段代码中存在一些问题。如果代码只使用注释掉的 removeChild 行,它会告诉我 e.currentTarget 不为 null,但它也不是对 Bullet 类型实例的引用(即“as”强制转换返回 null)。

【讨论】:

  • 你知道,你是对的——我忘了​​我在之前的条件语句之外留下了痕迹。
【解决方案2】:

尝试颠倒这些行
可能通过对象引用丢失了对 e.currentTarget 的引用

e.currentTarget.removeEventListener(e.type,arguments.callee);
e.currentTarget.parent.removeChild(shot);

e.currentTarget.parent.removeChild(shot);
e.currentTarget.removeEventListener(e.type,arguments.callee);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2011-06-28
    相关资源
    最近更新 更多