-1

我是使用 AS3 编程的新手,从相当旧的 MJW AvoiderGame 教程开始。由于本教程有点旧,我在尝试学习 AS3 时遇到了很多错误。现在我遇到了一个我无法弄清楚的错误。

TypeError: Error #1009: Cannot access a property or method of a null object reference.
at AvoiderGame/onTick()
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()

问题似乎出在 AvoiderGame 类中的 onTick 函数中。这是 AvoiderGame 类:

package 
{
    import flash.display.MovieClip;
    import flash.utils.Timer;
    import flash.events.TimerEvent;

public class AvoiderGame extends MovieClip 
{
    public var army:Array;
    public var enemy:Enemy;
    public var avatar:Avatar;
    public var gameTimer:Timer;
    public var gameClock:Clock;

    public function AvoiderGame() 
    {
        army = new Array();
        var newEnemy = new Enemy( 200, -15 );
        army.push( newEnemy );
        addChild( newEnemy );

        avatar = new Avatar();
        addChild( avatar );
        avatar.x = mouseX;
        avatar.y = mouseY;

        gameTimer = new Timer( 25 );
        gameTimer.addEventListener( TimerEvent.TIMER, onTick );
        gameTimer.start();
    }

    public function onTick( timerEvent:TimerEvent ):void 
    {
        gameClock.addToValue( 25 );
        if ( Math.random() < 0.1 )
        {
            var randomX:Number = Math.random() * 800;
            var newEnemy:Enemy = new Enemy( randomX, -15 );
            army.push( newEnemy );
            addChild( newEnemy );
            gameScore.addToValue( 10 );
        }
        avatar.x = mouseX;
        avatar.y = mouseY;

        for each ( var enemy:Enemy in army ) 
        {
            enemy.moveDownABit();
            if ( avatar.hitTestObject( enemy ) ) 
            {
                gameTimer.stop();
                dispatchEvent( new AvatarEvent( AvatarEvent.DEAD ) );
            }
        }
    }

    public function getFinalScore():Number
    {
        return gameScore.currentValue;
    }

    public function getFinalClockTime():Number
    {
        return gameClock.currentValue;
    }
}

}

4

1 回答 1

3

这很明显 -onTick()第一行是

gameClock.addToValue( 25 );

但是您从不初始化该gameClock字段。这样它就具有默认null值,因此您会看到错误。您应该按照初始化gameTimer字段的方式相应地对其进行初始化。

于 2013-08-05T07:50:30.743 回答