Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

exit

menu

xna

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?

like image 477
TheQuantumBros Avatar asked Dec 09 '22 15:12

TheQuantumBros


1 Answers

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.

like image 100
Daniel Masterson Avatar answered Dec 11 '22 09:12

Daniel Masterson