繁体   English   中英

XNA - 如何从主要课外退出游戏?

[英]XNA - How to Exit Game from class other than main?

你怎么做到这样游戏可以退出但没有主类中的代码,让它在不同的类?

您可以创建一个方法:

//Inside of game1.cs
public void Quit()
{
    this.Exit()
}

我假设您想要在菜单组件上退出游戏,在这种情况下,您需要将game1的实例传递给组件,或者将其作为菜单组件更新方法中的参数添加。

public void Update(GameTime gameTime, Game1 game)
{
     if(key is pressed)
     {
          game.Quit();
     }
}

我不确定是否还有其他方法......也许找到一种方法来“强制”按下关闭按钮。

为了发送game1.cs的实例:

//in game1.cs
//in your update method
public void Update(GameTime gameTime)
{
     //sends the current game instance to the other classes update method, where
     // quit might be called.
     otherClass.Update(gameTime, this);
     //where 'this' is the actual keyword 'this'. It should be left as 'this'
}

您还可以使用一种单例模式,在主游戏类中,您可以定义该类类型的静态变量。 在构造或初始化该类时,然后将该变量设置this ,允许您在任何地方都可以轻松访问类的实例。

public class Game1 : Microsoft.Xna.Framework.Game
{
    public static Game1 self;

    public Game1()
    {
        self = this;
        //... other setup stuff ...
    }

    //... other code ...
}

然后,当你想从代码中的任何地方调用这个类中的方法时,你只需:

Game1.self.Exit(); //Replace Exit with any method

这是有效的,因为通常只有一个Game类存在。 当然,如果你以某种方式拥有多个Game类,这种方法也无法正常工作。

在您的主游戏类(默认为Game1 )中使用全局变量:

public static Boolean exitgame = false;

在Game1更新例程中:

protected override void Update(GameTime gameTime)
{    
     SomeOtherClass.Update(gameTime);
     if (exitgame) this.Exit();
     base.Update(gameTime);
}

您可以告诉XNA引擎立即关闭,如下所示:

Game.Exit();

这将立即退出游戏。 请注意,我说Game.Exit() - 游戏应该是你的游戏实例。 如果您在实现Game的类中进行编码,则可以执行以下操作:

Exit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM