How do I unload content from the content manager?

别说谁变了你拦得住时间么 提交于 2019-11-28 12:10:11
Andrew Russell

Take a look at my answers here and possibly here.

The ContentManager "owns" all the content that it loads and is responsible for unloading it. The only way you should unload content that a ContentManager has loaded is by using ContentManager.Unload() (MSDN).

If you are not happy with this default behaviour of ContentManager, you can replace it as described in this blog post.

Any textures or other unload-able resources that you create yourself without going through ContentManager should be disposed (by calling Dispose()) in your Game.UnloadContent function.

If you want to dispose a texture, the easiest way to do it:

    SpriteBatch spriteBatch;
    Texture2D texture;
    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        texture = Content.Load<Texture2D>(@"Textures\Brick00");
    }
    protected override void Update(GameTime gameTime)
    {
        // Logic which disposes texture, it may be different.
        if (Keyboard.GetState().IsKeyDown(Keys.D))
        {
            texture.Dispose();
        }

        base.Update(gameTime);
    }
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.LinearWrap, DepthStencilState.None, RasterizerState.CullCounterClockwise, null);

        // Here you should check, was it disposed.
        if (!texture.IsDisposed)
            spriteBatch.Draw(texture, new Vector2(resolution.Width / 2, resolution.Height / 2), null, Color.White, 0, Vector2.Zero, 0.25f, SpriteEffects.None, 0);

        spriteBatch.End();
        base.Draw(gameTime);
    }

If you want to dispose all content after exiting the game, the best way to do it:

    protected override void UnloadContent()
    {
        Content.Unload();
    }

If you want to dispose only texture after exiting the game:

    protected override void UnloadContent()
    {
        texture.Dispose();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!