参数child在AS3中必须是非null错误

时间:2012-08-27 06:50:52

标签: actionscript-3 flash null flash-cs5

我有一个暂停游戏的代码,它运行暂停功能,如下所示:

public function onKeyPress(keyboardEvent:KeyboardEvent) :void
{
    //Check for pause
    if(keyboardEvent.keyCode == Keyboard.P)
    {
        //If the timer is still running
        if(gameTimer.running)
        {
            gameTimer.stop();
            Mouse.show();
            pauseText = new PauseText();
            pauseText.x = 150;
            pauseText.y = 100;
            addChild(pauseText);
            //If the player is using the mouse, resume by clicking on the player
            if(mouseControl)
            {
                player.addEventListener(MouseEvent.CLICK, resumeGame);
                pauseText.pauseInformation.text = "click on yourself";
            }
            else
            {
                pauseText.pauseInformation.text = "press 'p'";
            }
        }
        else
        {
            //Only allow the player to resume with P IF he is using the keyboard
            //This prevents cheating with the mouse.
            if(!mouseControl)
            {
                gameTimer.start();
                removeChild(pauseText);
                pauseText = null;
            }
        }
    }
}

游戏运行完美。在我的第一个游戏中,暂停功能起作用。但是,如果以后我死了并重新启动游戏,然后暂停它,我收到以下消息:

TypeError: Error #2007: Parameter child must be non-null.
    at flash.display::DisplayObjectContainer/removeChild()
    at Game/onKeyPress()

游戏仍然运行良好。但是,每次暂停或取消暂停时,都会出现此错误。如果我再次死亡,重新启动,然后暂停,会出现其中两个错误。从我可以收集它似乎它试图删除pauseText ...但我已经删除它就好在第一个playthrough,我已经使用removeChild()然后设置为null我的代码的其他部分,它的工作原理精细。另外,如果我添加一个跟踪(“a”);在函数头之后的语句,我在输出面板上出现“a”之前得到错误。

怎么了?

附加说明: 如果我在第一次播放时根本不使用暂停功能,那么当我在第二次播放时调用它时没有错误。

3 个答案:

答案 0 :(得分:0)

将removeChild放入'if',这将解决错误:

if(pauseText.parent){
    pauseText.parent.removeChild(pauseText);
}

但无论如何你应该检查问题的根源,也许'gameTimer.running'在开始时是假的?

答案 1 :(得分:0)

您可能会实例化另一个游戏对象(包含整个游戏的游戏对象),而不会移除上一个游戏的事件监听器。这可以解释这种行为,因为你有多个KeyboardEvent.KEY_DOWN监听器处于活动状态,并注意到当你停止游戏时,你很可能会停止其中的计时器,所以你的“if”(游戏时间)的“else”条款.running)“语句被执行,但计时器有效停止,没有生成pauseText。所以,你错过了

removeEventListener(KeyboardEvent.KEY_DOWN,onKeyPress);

在您的游戏销毁代码中。

答案 2 :(得分:0)

if (!mouseControl) {
    gameTimer.start();
    if (pauseText && contains(pauseText)) {
        removeChild(pauseText);
        pauseText = null;
    }
}