2012-07-21 51 views
0

我正在用XNA编码我的第一款游戏,而且我有点困惑。如何加载和卸载关卡

该游戏是一个2D平台游戏,以像素为完美,不是基于瓷砖。

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

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是个好主意。

好了,这里是我的问题:

  • 我怎样才能保存自己的数字精灵,它们的事件和对象的水平?
  • 如何加载/卸载这些级别?

回答

5

给每个级别的它自己的ContentManager,并用它来代替Game.Content(每级内容)。

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

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

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

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

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

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

请记住,这是一个优化(内存) - 所以不要花太多时间,直到它变成实际问题。

我推荐阅读this answer(在gamedev网站上),它提供了一些提示和进一步解答的链接,以更深入地解释ContentManager的工作原理。

+0

你说得对,我不应该浪费太多时间。但总是很高兴知道。 Thx对于所有这些信息都很重要。 – Sharpnel 2012-07-21 12:25:04

+0

奖励:在游戏关卡文件中,您应该保密和完整。前者为了避免用户在文件内部偷看以在实际播放它之前知道该级别,后者避免用户改变级别数据以便在玩它时获得一些益处 – 2014-04-17 21:17:36