First i’ll just state that I’m using singletons that won’t actually be around throughout the entire app life time. It’s more a way of encapsulating what is going on from the user.
I have several GameStates, eg InGame or MainMenu, and these have some quite similar function calls so I thought to use inheritence to stop copy / pasting. The following code is what I have, but it does not work as I intend. Here it is:
BaseState.cs
abstract class BaseState
{
protected static BaseState mHandle = null;
protected static BaseState Handle
{
get
{
return mHandle;
}
set
{
mHandle = value;
}
}
public static GameState UpdateState(GameTime gameTime)
{
GameState g = GameState.MainMenu;
try
{
Handle.Update(gameTime);
}
catch (Exception e)
{
}
return g;
}
public static void DrawState(GameTime gameTime, SpriteBatch spriteBatch)
{
Handle.Draw(gameTime, spriteBatch);
}
public static void Release()
{
mHandle = null;
}
protected abstract GameState Update(GameTime gameTime);
protected abstract void Draw(GameTime gameTime, SpriteBatch spriteBatch);
}
InGame.cs
class InGame : BaseState
{
private InGame()
{
}
protected static new BaseState Handle
{
get
{
if (mHandle == null)
{
mHandle = new InGame();
}
return mHandle;
}
set
{
mHandle = value;
}
}
protected override GameState Update(GameTime gameTime)
{
return GameState.Quit;
}
protected override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
}
}
You can probably tell that I want to be able to use the get and set of InGame in the BaseState so I can simply call Handle.Update() and no matter if I called it from InGame or Menu or whatever it would know which code to use.
Obviously I need to brush up on my OO skills. But if anyone could suggest a way to get this to do what I would like it to, or to suggest a different way of going about it I would be grateful. Thanks.
What you are trying to achieve does not require a singleton, see below: