【发布时间】:2010-11-24 09:03:31
【问题描述】:
我尝试在 texture2d 上使用 dispose 函数,但这会导致问题,我很确定这不是我想要使用的。
我应该使用什么来基本卸载内容?内容管理器会自行跟踪还是我必须做些什么?
【问题讨论】:
我尝试在 texture2d 上使用 dispose 函数,但这会导致问题,我很确定这不是我想要使用的。
我应该使用什么来基本卸载内容?内容管理器会自行跟踪还是我必须做些什么?
【问题讨论】:
ContentManager“拥有”它加载的所有内容并负责卸载它。卸载 ContentManager 已加载内容的唯一方法是使用 ContentManager.Unload() (MSDN)。
如果您对 ContentManager 的这种默认行为不满意,可以按照this blog post 中的说明替换它。
您自己创建的任何纹理或其他可卸载资源都应通过ContentManager 处理(通过调用Dispose())在您的Game.UnloadContent 函数中。
【讨论】:
Dispose(bool disposing)(这是一种受保护的方法,不能从外部调用)。这是标准 C# 一次性模式 (explained here) 的一部分。 Dispose(true) 在标准处理期间被调用(using 语句或直接调用 Dispose()),并且本身将调用 Unload()。 Dispose(false) 被终结器调用,特别是不调用Unload(它无法访问其他对象,它们可能已经被终结了)。
如果要处理纹理,最简单的方法是:
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();
}
【讨论】: