【问题标题】:How do I unload content from the content manager?如何从内容管理器中卸载内容?
【发布时间】:2010-11-24 09:03:31
【问题描述】:

我尝试在 texture2d 上使用 dispose 函数,但这会导致问题,我很确定这不是我想要使用的。

我应该使用什么来基本卸载内容?内容管理器会自行跟踪还是我必须做些什么?

【问题讨论】:

标签: xna content-management


【解决方案1】:

看看我的回答 here 可能还有 here

ContentManager“拥有”它加载的所有内容并负责卸载它。卸载 ContentManager 已加载内容的唯一方法是使用 ContentManager.Unload() (MSDN)。

如果您对 ContentManager 的这种默认行为不满意,可以按照this blog post 中的说明替换它。

您自己创建的任何纹理或其他可卸载资源都应通过ContentManager 处理(通过调用Dispose())在您的Game.UnloadContent 函数中。

【讨论】:

  • 还有一个 ContentManager.Unload(bool disposing) 如果为真,它也被描述为卸载托管内容。 xna 库中是否存在需要手动处置的 xna 内容类型?
  • @Wouter Unload 在我在 MSDN 上看到的任何版本中都没有参数。您可能正在查看Dispose(bool disposing)(这是一种受保护的方法,不能从外部调用)。这是标准 C# 一次性模式 (explained here) 的一部分。 Dispose(true) 在标准处理期间被调用(using 语句或直接调用 Dispose()),并且本身将调用 Unload()Dispose(false) 被终结器调用,特别是不调用Unload(它无法访问其他对象,它们可能已经被终结了)。
【解决方案2】:

如果要处理纹理,最简单的方法是:

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

如果你想在退出游戏后处理所有内容,最好的方法是:

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

如果你想在退出游戏后只处理纹理:

    protected override void UnloadContent()
    {
        texture.Dispose();
    }

【讨论】:

    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多