AS3在计时器变量上获得错误#1009

问题描述:

我遇到错误#1009:无法访问空对象引用的属性或方法。我并不确定如何自己解决这个问题,我追踪了解对象var enemySpawnTimer:Timer是否实际为空,而不是。所以我不明白为什么我会得到这个错误。AS3在计时器变量上获得错误#1009

无论如何,这里是我的代码,它是我用来产生从屏幕顶部到底部的块的类,并且一旦到达屏幕底部就从舞台上移除。

package scripts 
{ 
    import flash.events.Event; 
    import flash.display.Stage; 
    import flash.events.Event; 
    import flash.events.TimerEvent; 
    import flash.utils.Timer; 
    import flash.display.DisplayObject; 

    public class EnemySpawner 
    { 
     var stageRef:Stage; 
     var target:Player; 

     //vector variables 
     public static var vectorBlock:Vector.<Block> = new Vector.<Block>(); 

     //enemy variables 
     public static var block:Block; 

     //timer variables 
     var enemySpawnTimer:Timer = new Timer(250); 

     //score variables 
     public static var pointsBlock:Number = 0; 

     public function EnemySpawner(stageRef:Stage, target:Player) 
     { 
      this.stageRef = stageRef; 
      this.target = target; 

      enemySpawnTimer.addEventListener(TimerEvent.TIMER, SpawnBlocks, false, 0, true); 
      enemySpawnTimer.start(); 
     } 

     private function SpawnBlocks(e:TimerEvent):void 
     { 
      block = new Block(stageRef); 
      pointsBlock = block.pointsGiven; 

      vectorBlock.push(block); 
      stageRef.addChild(block); 

      block.addEventListener(Event.ENTER_FRAME, Update, false, 0, true); 
     } 

     private function Update(e:Event):void 
     { 
      //remove enemies when they pass the bottom of the stage 
      for each(var block:Block in vectorBlock) 
      { 
       if(block.y > Bounds.rectH + block.height) 
       { 
        RemoveFromList(block); 
       } 
      } 

      target.addEventListener("playerDeath", StopSpawning, false, 0, true); 
     } 

     private function RemoveFromList(block:Block):void 
     { 
      vectorBlock.splice(vectorBlock.indexOf(block), 1); 

      if(stageRef.contains(block)) 
      { 
       stageRef.removeChild(block); 
      } 
     } 

     private function StopSpawning(e:Event):void 
     { 
      enemySpawnTimer.stop(); 
     } 
    } 
} 

这是我得到的错误,不幸的是,在Flash中使用脚本编辑器并不太有助于导致错误的位置或内容。

TypeError: Error #1009: Cannot access a property or method of a null object reference. 
at scripts::EnemySpawner/SpawnBlocks() 
at flash.utils::Timer/_timerDispatch() 
at flash.utils::Timer/tick() 
+0

它可能不是定时器导致您的空指针异常。错误信息是否有其他说明,你有行号还是其他的? – weltraumpirat 2011-02-22 20:20:13

+0

我加了错误。不幸的是我没有得到行号,除非它在编译时出错。我曾经想过在所有地方放置“跟踪”语句来找出可能为空的东西,但我不知道我在找什么,所以抛出跟踪语句可能毫无意义。 – RamenNoodles 2011-02-22 20:58:20

如果我正确理解错误的最后一点,是不是必须是空的SpawnBlocks()方法内的东西?我会看stageRef和vectorBlock,也许block.pointsGiven。

这个错误时,东西为空,通常会出现,我最好的猜测是“stageRef” 尝试之前

this.stageRef = stageRef; 

一个你可以为更好的调试做更多的事情将

stageRef = new Stage(); 

是允许它,请点击文件/发布设置/闪存并勾选“许可证调试“,然后再次重新发布以查看您的错误,这次它会让您知道导致错误的帧和行号。