flixel

Switching FlxStates


I'm having an issue when I try to switch back to my PlayState after going into my menu state. When I click "go back" on my menu state, I get an error stating that "[Fault] exception, information=TypeError: Error #1009: Cannot access a property or method of a null object reference" when the game tries to add a button in the PlayState after leaving my menu state. Here's a clip of the PlayState code for testing:

public class PlayState extends FlxState
{
    override public function create():void
    {
        // ...
        add(new FlxButton(0, 0, "test"));
    }
}

and here's my menu state:

import org.flixel.*;

public class stand_menu extends FlxState 
{
    public var ps:PlayState;
    public function stand_menu(PS:PlayState) 
    {
        ps = PS;
    }
    override public function create():void
    {
        FlxG.bgColor = 0xFFFFFFFF;
        var bttn:FlxButton = new FlxButton(10, 10, "add cash",add_cash);
        this.add(bttn);
        var bttn2:FlxButton = new FlxButton(10, 30, "go back",go_back);
        this.add(bttn2);
    }
    public function add_cash():void
    {
        ps.cash += 10;
    }
    public function go_back():void
    {
        FlxG.switchState(ps);
    }
}

Solution

  • I'm not sure that states are meant to be used like that.

    if you open follow the code from FlxG.switchState(state), you'll end in FlxGame.switchState, where this happens

    protected function switchState():void
        { 
            //.... skipping some code here
    
            //The old state is officially destroyed
            if(_state != null)
                _state.destroy();
    
            //And actual state switching is done here. Note that _requestedState was set from FlxG.switch state
            _state = _requestedState;
            _state.create();
        }
    

    Practically, when you change states, the old one is destroyed. So FlxG.switchState() is not meant to be used to load old states, it will only work for new ones. You usually create a new state every time you switch to it. eg:

    public static function quitToMainMenu():void {
            FlxG.switchState(new MainMenuState);
        }
    

    If you need to store things in a state, and use them later, don't do it. Put them in another static or singleton class, so they won't get deleted once you change your state.