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

南笙酒味 提交于 2019-12-10 19:27:31

问题


How do you make it so the game can exit but not have the code in the main class, have it in a different class?


回答1:


You can create a method:

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

I'm assuming you want to quit the game on a menu component, in which case you will need to pass the instance of game1 to the component, perhaps add it as a parameter in the menu components update method.

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

I'm not sure if there are any other ways... Perhaps finding a way to "force" the close button to press.

In order to send the instance of 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'
}



回答2:


You can also use a sort of singleton pattern, whereby in your main game class you define a static variable of the type of that class. When you construct or initialize that class, you then set that variable to this, allowing you to have an easily accessible reference to the instance of the class anywhere.

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

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

    //... other code ...
}

Then, when you want to call a method in this class from pretty much anywhere in code, you would simply do:

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

This works as there should only usually be a single Game class in existence. Naturally, if you were to somehow have multiple Game classes, this method won't work as well.




回答3:


In your main game class (Game1 by default) use a global variable:

public static Boolean exitgame = false;

In the Game1 update routine:

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



回答4:


You can tell the XNA engine to close immediately like this:

Game.Exit();

This will immediately exit the game. Note that I say Game.Exit() - Game should be your game instance. If you are coding within a class that implements Game, you can simply do the following:

Exit()



来源:https://stackoverflow.com/questions/16556071/xna-how-to-exit-game-from-class-other-than-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!