I've been trying to learn MonoGame from their official documentation.
However, I've hit a snag.
In their code, they've done the following...
Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X,
GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.Height / 2);
Now, the problem I'm getting is this. Whenever I use the bit of code GraphicsDevice.Viewport
, MonoGame does not allow it and gives the following error:
An object reference is required for the non-static field, method or property 'GraphicsDevice.Viewport'
What can I do to fix this error?
This is not really a MonoGame problem. It's got to do with the way C# resolves properties and types.
If we take a look at the Viewport
property of GraphicsDevice
we can see that it's a non-static property of the GraphicsDevice
class.
public class GraphicsDevice
{
public Viewport Viewport { get; set; }
}
The other piece to this puzzle is that there's also a GraphicsDevice
property on the Game
class.
public class Game
{
public GraphicsDevice GraphicsDevice { get; }
}
What this means is that when you use the line GraphicsDevice.Viewport
within the context of the Game
class, it has a different meaning to when you use it outside the context of the Game
class.
For example, if you put your code inside the Update
method of a class that derives from Game
it will work.
public class Game1 : Game
{
public void Update(GameTime gameTime)
{
Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.Height / 2);
}
}
The reason this works, is because it's using the GraphicsDevice
property from the base Game
class in this context.
On the other hand, if you put the same code inside a class that doesn't have a GraphicsDevice
property you'll get the error in your question.
public class MyClass
{
public void Update(GameTime gameTime)
{
Vector2 playerPosition = new Vector2(GraphicsDevice.Viewport.TitleSafeArea.X, GraphicsDevice.Viewport.TitleSafeArea.Y + GraphicsDevice.Viewport.Height / 2);
}
}
I suspect the cause is something like that, although, it's difficult to tell with the limited information in your question.
There's multiple ways to solve this problem. One way is to inject the GraphicsDevice
into the constructor of your custom class and use that instead.
public class MyClass
{
private GraphicsDevice _graphicsDevice;
public MyClass(GraphicsDevice graphicsDevice)
{
_graphicsDevice = graphicsDevice;
}
public void Update(GameTime gameTime)
{
Vector2 playerPosition = new Vector2(_graphicsDevice.Viewport.TitleSafeArea.X, _graphicsDevice.Viewport.TitleSafeArea.Y + _graphicsDevice.Viewport.Height / 2);
}
}
I hope that helps.