如何在不同的类中使用Monogame GraphicsDeviceManager?

时间:2018-07-13 12:26:25

标签: c# monogame

我有一个类,该类具有在屏幕上绘制形状的方法。

public class Rectangle : Game1 {

    Texture2D quadl;

    public Rectangle() {    

    }

    public void size() {

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

    }    
}

然后我在Game1类更新方法中调用它

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

然后产生无限循环。

出什么问题了?以及如何解决? 我怀疑这与GraphicsDeviceManager有关,但是我没有找到任何帮助。

1 个答案:

答案 0 :(得分:1)

您的矩形不应继承自Game1。如果需要访问GraphicsDevice,请将其作为参数传递给构造函数。因为现在,您正在为每个矩形创建一个新的Game1。

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);
    }    
}

由于我们现在正在做的事情,您正在使用每个Rectangle创建游戏的新实例,每个Rectangle都有自己的GraphicsDevice实例。