2013-07-23 48 views
0

所以,我的問題如下。試圖用鼠標點擊刪除孩子

爲什麼會出現這個錯誤

(類型錯誤:錯誤#2007:參數孩子必須爲非空 在flash.display使用::級DisplayObjectContainer/removeChild之() 在TargetMain/killTarget()。)

當試圖通過鼠標點擊從舞臺上刪除對象?

我的應用程序代碼如下。

package 
{ 
    import flash.display.*; 
    import flash.events.*; 
    import flash.text.*; 
    import flash.ui.Keyboard; 

    public class TargetMain extends MovieClip 
    { 
     public function TargetMain() 
     { 
      stage.addEventListener(KeyboardEvent.KEY_DOWN, spawner);//Spawning function listener 

      stage.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener 
     } 

     public function spawner(k:KeyboardEvent):void 
     { 
      if(k.keyCode == 32) 
      { 
       trace ("spawned"); 
       var theTarget:ParaspriteFull = new ParaspriteFull(); 

       theTarget.x = Math.floor(Math.random() * stage.stageWidth); 
       theTarget.y = Math.floor(Math.random() * stage.stageHeight); 
       addChild(theTarget); 

      } 
     } 

     public function killTarget(toDie:MouseEvent):void 
     { 
      trace ("clicked") 
      var deadTarget:ParaspriteFull = (toDie.target as ParaspriteFull); 
      //Below is where I continually get an error and do not know how to fix it. 
      //This is also after searching the internet for hours trying to solve my issue. 

      //MovieClip(deadTarget).parent.removeChild(deadTarget); 
      removeChild(deadTarget); 
     } 
    } 
} 

任何幫助,非常感謝。

回答

0

的錯誤意味着deadTarget是空的,所以如果你只是想從舞臺上刪除deadTarget,試試這個

var deadTarget:DisplayObject = toDie.target as DisplayObject; 

if (deadTarget && deadTarget.parent) { 
    deadTarget.parent.removeChild(deadTarget); 
} 

或者你應該找出實際活動類型deadTarget的。

0

您正在聽點擊舞臺。因此,任何點擊(無論是否在ParaspriteFull對象上)都會觸發killTarget。避免異常的一種方法是按Pan的回答建議,如果點擊的對象不是ParaspriteFull類型,則點擊killTarget時基本不做任何事情。 但是,我建議聽聽ParaspriteFull對象的點擊,而不是在舞臺上。即從constructor刪除

stage.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener 

和修改spawner功能添加點擊監聽器:

theTarget.addEventListener(MouseEvent.CLICK, killTarget);//Clicking function listener 

此外,在killTarget刪除監聽器ParaspriteFull對象爲:

deadTarget.removeEventListener(MouseEvent.CLICK, killTarget);//Remove clicking function listener