2
\$\begingroup\$

I have found this post explaining about how to get the size of the Window, but for whatever reason I'm having issues getting it to work inside of a Singleton class that I'm made to manage a set of Objects. Anyone have any examples of getting these values from inside of a singleton?

EDIT: Just in case the question gets asked. I'm using the values for when the Manager instantiate the objects it's managing... So that they don't all start at the same spot and to ensure they start on the screen.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Method 1 - Provide global access to Game

The simplest way I can think of is to provide global access to your Game instance:

public class MyGame : Microsoft.Xna.Framework.Game
{
    public static MyGame Instance;
    public MyGame () { Instance = this; }
}

After which you can simply do MyGame.Instance.GraphicsDevice.Viewport.Bounds or any of the other alternatives Andrew suggested in the other question. This would work from anywhere in your application, granted the game has already been created which should always be the case anyway.


Method 2 - Pass a reference to Game to your class

Alternatively, pass a reference to Game to your class. If you're using a singleton class (do you really need to?) and your constructor needs to remain empty, use a separate Initialize method instead:

public class MySingleton
{
    public void Initialize(Game game) { _game = game; }
    private Game _game;
}

After which you can access it as _game.GraphicsDevice.Viewport.Bounds from within your class. Don't forget to call Initialize when starting the game though (i.e. calling MySingleton.Instance.Initialize(this) from within your Game).


Method 3 - Make your class a GameComponent

If your manager inherits from GameComponent or DrawableGameComponent, then it's already guaranteed to hold a valid reference to a Game object. You'll need to pass this reference to the constructor when instantiating your manager.

public class MyClass : GameComponent
{
    public MyClass(Game game) : base(game) { }
}

In this case you can access it as Game.GraphicsDevice.Viewport.Bounds from within your class.

\$\endgroup\$
1
  • \$\begingroup\$ As far as needing a Singleton? Not sure I'm mainly playing around. Just started a Game Development class so still just playing around with the framework. Excellent answer though. Thank you. \$\endgroup\$
    – Jared
    Commented Jan 28, 2012 at 19:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .