Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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.

share|improve this answer
    
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. –  Jared Jan 28 '12 at 19:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.