XNA close the game

So, I create a game for fun :) and at a certain point I am trying to close the game.

I found that to close the game I need to use the Exit () function in Game1, so I tried the following code:

Game1.GetInstance().Exit(); 

GetInstance is my own method that returns an instance of Game1 so that I can exit the game from other classes.

How can I close a game from another class? What I did was save the pointer to the game1 instance in the constructor of game1, and then I can return it to use it in other classes. Hope this was clear (sorry if not).

So how to use the exit function from other classes?

+4
source share
3 answers

You can create a method in the class game1

 public void Quit() { this.Exit(); } 

Now in another class that you want to exit, you can add a link to your main class

 public class SomeOtherClassYouWantToExitFrom { public Game1 game; //Reference to your main class public void DoStuff() { //Do Stuff game.Quit(); } } 

When you create the SomeOtherClassYouWantToExitFrom class, you need to set the game object as an instance of Game1. You can also pass it as an argument to constuctor

  Blah = new SomeOtherClassYouWantToExitFrom(...) { game = this }; 

Using the Exit method is great for me, I'm not sure why Visual Studio thinks it is still debugging.

+5
source

If Game1 is a singleton, it should work, you can always use the enumeration from Game1, and then exit to Game1.

0
source

I am using MonoGame version 3.4, but I came across this question while trying to solve the problem myself ...

Here is what I did, which works very well (I needed to exit a class that does not exist in Game1)

I noticed that Program.cs was already a static class, so I used this:

 // Program.cs using System; namespace XnaGame { #if WINDOWS || LINUX public static class Program { public static Game1 Game; [STAThread] static void Main() { using (var game = new Game1()) { Game = game; Game.Run(); } } } #endif } 

At this moment I have access to

  Program.Game.Exit () 
from anywhere in my game, while still using the provided using operation.
0
source

Source: https://habr.com/ru/post/1486272/


All Articles