Why does changing the graphics setting after doing

2019-08-13 02:35发布

问题:

If I set the graphics settings in the Initialize method and then in the Update method, like so:

protected override void Initialize()
{
    graphics.ApplyChanges();
    base.Initialize();
}

protected override void Update(GameTime gameTime)
{
    graphics.ApplyChanges();
    base.Update(gameTime);
}

Everything is fine.

However, when I move the code to my LoadContent method like so:

protected override void LoadContent()
{
    spriteBatch = new SpriteBatch(GraphicsDevice);
    graphics.ApplyChanges();
}

protected override void Update(GameTime gameTime)
{
    graphics.ApplyChanges();
    base.Update(gameTime);
}

I get an InvalidOperationException:

Must call BeginScreenDeviceChange before calling EndScreenDeviceChange

This doesn't make much sense to me, since I'm doing the same thing in both. It was my understanding that the LoadContent method was simply called after the Initialize method. What is happening between those calls that messes up the GraphicsDeviceManager?

回答1:

You're messing up some of XNA's internal plumbing. Normally XNA should hook up events to call those methods on GameWindow when the graphics device is created/destroyed, with correct pairing. But, because you're changing the graphics device somewhere you shouldn't be, you've somehow caused it to fail.

To answer the question about your specific case: What is happening is that base.Initialize() calls LoadContent after it has set up those events. Your call to ApplyChanges has moved from before the events get hooked up, to after.

Not that it matters, because neither version of your code is correct. That it seems to work in the first version is just good luck. Please see this answer, which explains how to set up and change the graphics device correctly.