如何加载和卸载级别

问题描述 投票:1回答:1

我正在用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
}

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

好吧,这是我的问题:

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

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

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

单个ContentManager将共享它加载的所有内容实例(因此,如果您加载“MyTexture”两次,则两次都会获得相同的实例)。由于这个事实,卸载内容的唯一方法是卸载整个内容管理器(使用.Unload())。

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

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

解决这个问题的最简单方法是使用Game.Content加载所有“共享”内容,并使用单独的级别内容管理器加载所有每个级别的内容。

如果仍然无法提供足够的控制,您可以从ContentManager派生一个类并实现自己的加载/卸载策略(example in this blog post)。虽然这很少值得努力。

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

我建议阅读this answer(在gamedev网站上),提供一些提示和链接,以进一步解释ContentManager如何工作的更多答案。

© www.soinside.com 2019 - 2024. All rights reserved.