0

我正在使用 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++;
        }
}
}
}

提前致谢。

4

1 回答 1

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(); 
    }
}
于 2012-11-13T22:08:36.603 回答