AS3:错误1009:空引用

时间:2012-11-13 20:33:10

标签: actionscript-3 reference null

我正在使用ActionScript 3制作游戏。我有一个菜单类,其中包含一个呈现菜单的方法。 我在Main类中创建了一个Menu实例,然后调用该方法。当我调试应用程序时,我得到一个空引用错误。这是菜单类的代码:

package
{
import flash.display.MovieClip;

import menucomponents.*;

public class Menu extends MovieClip
{
    public function Menu()
    {
        super();
    }

    public function initMenuComponents():void{
        var arrMenuButtons:Array = new Array();

        var btnPlay:MovieClip = new Play();
        var btnOptions:MovieClip = new Options();
        var btnLikeOnFacebbook:MovieClip = new LikeOnFacebook();
        var btnShareOnFacebook:MovieClip = new ShareOnFacebook()

        arrMenuButtons.push(btnPlay);
        arrMenuButtons.push(btnOptions);
        arrMenuButtons.push(btnLikeOnFacebbook);
        arrMenuButtons.push(btnShareOnFacebook);

        var i:int = 0;

        for each(var item in arrMenuButtons){
            item.x = (stage.stageWidth / 2) - (item.width / 2);
            item.y = 100 + i*50;
            item.buttonMode = true;

            i++;
        }
}
}
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您的for循环运行时,您的问题可能还没有填充阶段。请尝试以下方法:

public class Main extends MovieClip { 
    public function Main() { 
        super(); 
        var menu:Menu = new Menu(); 

        //it's good practice - as sometimes stage actually isn't populated yet when your main constructor runs - to check, though in FlashPro i've never actually encountered this (flex/flashBuilder I have)
        if(stage){
            addedToStage(null);
        }else{
            //stage isn't ready, lets wait until it is
            this.addEventListener(Event.ADDED_TO_STAGE,addedToStage);
        }
    } 

    private function addedToStage(e:Event):void {
        menu.addEventListener(Event.ADDED_TO_STAGE,menuAdded); //this will ensure that stage is available in the menu instance when menuAdded is called.
        stage.addChild(menu); 
    }

    private function menuAdded(e:Event):void {
        menu.initMenuComponents(); 
    }
}