2011-04-04 87 views
0

我在同時刪除事件偵聽器以及精靈時遇到問題。目前,我得到一個錯誤:同時刪除事件偵聽器以及精靈AS3

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

如果我註釋掉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(); 
     } 
    } 
+0

不要忘了把在shot.y < 0 - shot.height :) – 2011-04-04 21:47:02

+0

只是一點:通常當添加事件偵聽器時,使用弱引用即addEventListener(Event,shoot,false,0,true),這允許組件被垃圾收集並且類似於刪除eventListener – Ryan 2011-04-05 10:53:54

回答

0

除了子彈之前丟失VAR:子彈,我沒有看到任何錯誤的示例代碼。你應該後設置斷點右:

var shot:Bullet = e.currentTarget as Bullet; 

,弄清爲什麼拍攝爲空。作爲例子,我懷疑在你提供的一小部分代碼之外有一些代碼存在缺陷。如果代碼只處理removeChild行註釋掉,它告訴我e.currentTarget不是null,但它也不是對Bullet類型實例的引用(即「as」cast將返回null)。

+0

你知道,你是對的 - 我忘了我在前面的條件陳述之外留下了一條痕跡。 – toast 2011-04-05 14:40:44

0

嘗試扭轉這些線路
也許參考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);