Search code examples
c#monogame

How to use Monogame GraphicsDeviceManager in different class?


I have a class which has a method to draw a shape on screen.

public class Rectangle : Game1 {

    Texture2D quadl;

    public Rectangle() {    

    }

    public void size() {

        quadl = new Texture2D(this.GraphicsDevice, 100, 100);

    }    
}

I then call this in Game1 class update method

Rectangle rt = new Rectangle(); rt.size();

it then produces an infinite loop.

What's the problem? and how would I go around fixing it? i suspect it has something to do with the GraphicsDeviceManager, however I haven't found any help with it.


Solution

  • Your Rectangle should not inherit from Game1. If you need to access your GraphicsDevice, pass it as an argument to your constructor. Because right now, you are creating a new Game1 for each rectangle.

    public class Rectangle {
    
        Texture2D quadl;
        private readonly GraphicsDevice _graphicsDevice;
    
        public Rectangle(GraphicsDevice graphicsDevice) {    
            this._graphicsDevice = graphicsDevice;
        }
    
        public void size() {
            quadl = new Texture2D(this._graphicsDevice, 100, 100);
        }    
    }
    

    Because we what you are doing right now, you are creating a new instance of your game with each Rectangle, which will each have their own instance of the GraphicsDevice.