如何加载和卸载级别

Sha*_*nel 1 xna

我正在用XNA编写我的第一个游戏,我有点困惑.

该游戏是一款2D平台游戏,基于像素完美,基于NOT Tiles.

目前,我的代码看起来像这样

public class Game1 : Microsoft.Xna.Framework.Game
{
//some variables
Level currentLevel, level1, level2;

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

protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);

//a level contains 3 sprites (background, foreground, collisions)
//and the start position of the player
level1 = new Level(
new Sprite(Content.Load<Texture2D>("level1/intro-1er-plan"), Vector2.Zero),
new Sprite(Content.Load<Texture2D>("level1/intro-collisions"), Vector2.Zero),
new Sprite(Content.Load<Texture2D>("level1/intro-decors-fond"), Vector2.Zero),
new Vector2(280, 441));

level2 = new Level(
new Sprite(Content.Load<Texture2D>("level2/intro-1er-plan"), Vector2.Zero),
new Sprite(Content.Load<Texture2D>("level2/intro-collisions"), Vector2.Zero),
new Sprite(Content.Load<Texture2D>("level2/intro-decors-fond"), Vector2.Zero),
new Vector2(500, 250));

...//etc
}


protected override void UnloadContent() {}


protected override void Update(GameTime gameTime)
{

if(the_character_entered_zone1())
{
ChangeLevel(level2);
}
//other stuff

}

protected override void Draw(GameTime gameTime)
{
//drawing code
}

private void ChangeLevel(Level _theLevel)
{
currentLevel = _theLevel;
//other stuff
}
Run Code Online (Sandbox Code Playgroud)

每个精灵都从一开始就被加载,因此对于计算机的RAM来说并不是一个好主意.

好吧,这是我的问题:

  • 如何用他自己的精灵数量,事件和对象来保存关卡?
  • 我如何加载/卸载这些级别?

And*_*ell 6

给每个级别自己ContentManager,并使用它而不是Game.Content(对于每个级别的内容).

(ContentManager通过传递Game.Services给构造函数创建新实例.)

一个 ContentManager将分享它加载内容的所有实例(因此,如果您"MyTexture"两次,你会得到相同的这两次实例).由于这个事实,卸载内容的唯一方法是卸载整个内容管理器(with .Unload()).

通过使用多个内容管理器,您可以通过卸载获得更多粒度(因此您可以仅为单个级别卸载内容).

请注意,不同的实例ContentManager彼此不了解并且不会共享内容.例如,如果在两个不同的内容管理器上加载"MyTexture",则会获得两个单独的实例(因此您使用两倍的内存).

处理此问题的最简单方法是Game.Content使用单独的级别内容管理器加载所有"共享"内容,以及所有每个级别的内容.

如果仍然无法提供足够的控制,您可以从中派生一个类ContentManager并实现自己的加载/卸载策略(本博客文章中的示例).虽然这很少值得努力.

请记住,这是一种优化(对于内存) - 因此在它成为实际问题之前不要花太多时间.

我建议阅读这个答案(在gamedev网站上),它提供了一些提示和指向更深入解释如何ContentManager工作的更多答案的链接.