简体   繁体   中英

Null reference exception getting value from base class

I have a little engine (defined as public class ScreenManager : DrawableGameComponent ) to manage input and screens (with transitions etc.), who works with a public abstract class GameScreen . For menu screens I have an abstract class MenuScreen : GameScreen . I'm trying to get from class OptionsMenuScreen : MenuScreen a value stored in the main class of the game (the one called by Program.cs), but I always get NullReferenceException. I need that value because while starting application I need to get some option and these options can be changed from OptionsMenuScreen, but I want that changes from that screen automatically reflects on the rest of application, so a screen can base it's computation on that value, without force the user to reload entire application to get values in main class updated. I do this with

public ScreenManager ScreenManager
{
    get { return screenManager; }
    internal set { screenManager = value; }
}

ScreenManager screenManager;

in GameScreen.cs and

/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public void AddScreen(GameScreen screen, PlayerIndex? controllingPlayer)
{
    screen.ControllingPlayer = controllingPlayer;
    screen.ScreenManager = this;
    screen.IsExiting = false;

    // If we have a graphics device, tell the screen to load content.
    if (isInitialized)
    {
        screen.LoadContent();
    }

    screens.Add(screen);

    // update the TouchPanel to respond to gestures this screen is interested in
    TouchPanel.EnabledGestures = screen.EnabledGestures;
}

as method to add a Screen to ScreenManager' list of screens. But when I try to do something like

separateAxis = (ScreenManager.GameInstance as Main).SeparateAxis;

I get always NullReferenceException. Despite it works from other Screens (deriving directly from GameScreen, not MenuScreen).

Any ideas?

There are 2 posibilies from your code, either ScreenManager is null, or (ScreenManager.GameInstance as Main) is.


For the first case:

I think you're calling your problem line from within the option screen's constructor, or at least before the screenmanager's AddScreen method is called.

Move it to the screen's LoadContent method.

For the second case:

Check that GameInstance is an instance of Main .


It's worth noting that this is the GameStateManagement sample you're basing your code on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM