没有看到您的代码很难确定,但听起来您需要实现某种状态机。您需要能够保持对非活动/背景状态(窗口、游戏区等)的引用,以便在完成当前场景后恢复旧场景。
一种方法——也是我个人最喜欢的一种——是使用有限状态机 (FSM) 模式。
基本原则是有一堆对象(在这种情况下是场景),每次新场景开始时,您都会将该场景添加到堆栈顶部。场景结束后,将其从堆栈中移除(称为从堆栈中弹出)。
听起来很复杂,但实际上使用起来非常简单。这是一个简单的例子:
public class StateManager
{
private ContentManager Content { get; set; }
private Game1 Game { get; set; }
private Stack<Scene> sceneStack = new Stack<Scene>();
private GameState currentScene;
private GameState previousScene;
public StateManager(ContentManager content, Game1 game)
{
// Pretty common to pass one or both of these instances around in your code.
this.Game = game;
this.Content = content;
}
public void AddScene(GameState newScene)
{
// This is the crucial part. We are saving the state of the old scene.
if (currentScene != null)
this.previousScene = currentScene;
sceneStack.Push(newScene); // New scene is stacked 'on top' of the old one
this.currentScene = newScene;
}
public void Draw(SpriteBatch spriteBatch)
{
// Out in Game1.cs we are calling this method from within
// its own Draw() method.
this.currentScene.Draw(spriteBatch);
}
}
public class Scene : GameState
{
// Any state information needed for your scene like menus, terrain, etc
}
public abstract class GameState
{
// The base class for your Scenes which contains code relevant to all scene types.
// You could go a step further and make an interface as well.
public virtual void Draw(SpriteBatch spriteBatch)
{
// Logic to draw the game state. Textures, sprites, text, child
// elements contained inside this state, etc.
}
}
如您所见,通过此设置,StateManager(以及 Game1)的 Draw() 方法将始终主动渲染堆栈顶部的任何场景,这应该始终是使用 NewScene 添加的最新场景() 方法。
RemoveScene() 方法非常简单,因为您基本上颠倒了您在 NewScene() 中所做的操作。调用 sceneStack.Pop();并且顶部场景被移除,将前一个场景设置为 currentScene 将确保堆栈上的最后一个场景将在它离开的地方继续。
当然,您需要为真正的游戏添加更多逻辑,因为在一个场景中完成的事情可能会改变场景的外观或行为,但其中大部分都可以在Update() 方法(其工作原理与这里的 Draw() 方法基本相同)。
希望对您有所帮助。