0
votes

I am making a game in ActionScript 3. I have a Menu Class with a method that renders a Menu. I make an instance of Menu in my Main class, and then call the method. When I debug the application I get a null reference error. This is the code of the menu class:

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++;
        }
}
}
}

Thanks in advance.

1
use the debugger to see what's going on, and if you don't have a debugger handy, you can try to at least keep a logSam I am says Reinstate Monica
@SamIam I get the error at the line where I try to add an item to the stage. Does that mean the stage is null or my items are null? Sorry if this is a dumb question, i never learned debugging properly at my college.svdotbe
@SylvainVansteelandt and what line is that?Sam I am says Reinstate Monica
@SamIam I'm sorry, after posting this I tried to add in the beginning of my for each a statement: stage.addChild(item); But the problem remains, it's always the first line of the for each loop.svdotbe

1 Answers

0
votes

Your issue is likely that stage is not populated yet when your for loop runs. Try the following:

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(); 
    }
}