Reputation: 1158
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?
Upvotes: 0
Views: 1524
Reputation: 32448
There are 2 posibilies from your code, either ScreenManager
is null, or (ScreenManager.GameInstance as Main)
is.
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.
Check that GameInstance
is an instance of Main
.
It's worth noting that this is the GameStateManagement sample you're basing your code on.
Upvotes: 1