I have a bunch of screens that all inherit from a base abstract class called GameScreen. They include various buttons that, if pressed, I want to use to change the Current Screen. For now, I am trying to change the screen from startScreen to overviewScreen.
I have a variable in my Game1 class:
public GameScreen CurrentScreen;
Which is initially set as:
CurrentScreen = startScreen;
I then use the following lines to Update and Draw the game, based on which screen is the Current screen:
CurrentScreen.Update();
...
CurrentScreen.Draw(spriteBatch);
In my startScreen classs, I want to write something like this within the update method:
if (//Button is pressed)
{
game.CurrentScreen = overviewScreen;
}
Now clearly that won't work. But I can't see how to do it. Basically I want to access the CurrentScreen variable from within a class, and change it to whichever screen I want, and I feel like there must be a clean way to do this.
Let me know if any additional info is required, I feel like I haven't explained this at all well.
EDIT
startScreen and overviewScreen are classes that, primarily contain the Update and Draw methods for screens I want to display. GameScreen is a base class they all derive from. CurrentScreen is just meant to be a variable that determines which screen is active.
use the static objects
public static GameScreen CurrentScreen;
and same for the overviewScreen
Ok, notw it's cleaner for me. You could add few methods to your Game1
class
public void SwitchToStartScreen(){...}
public void SwitchToOverviewScreen(){...}
//etc
Then you could add a property to your startScreen
class (and other ones too)
public Game1 Parent {get;set;}
And force the constructor to pass Game1
object, in which you would assign that parameter to Parent
property. Then on particular condition you could just use
Parent.SwitchToOverviewScreen();
Accessing and changing properties manually from outer classes is violating object-oriented principles.
Also, use brief naming convention, because it's hard to understand what you wrote if one of class definitions uses Pascal case while other use Camel case. Your startScreen
has more like an object name, while it's used like a class name. Eithar that or you're not seeing the difference between class and an object. By default in C# Pascal case is used for declaring classes.
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.