While I am on a roll, here is a very short Unity post. Probably the most basic thing you can do with Unity… but, if you are super new to Unity and C# this is might be just the right thing to get you started…
Quit Application…
I remember when I first started using unity this was probably one of the first things I wrote… mostly because I got fed up with being in full screen post-build and there is no exit button thinking dammit…I forgot to make that dialog again! So I will quickly show a quick and dirty dialog for just that purpose…
Setup…
For this UI I made a really simple dialog as shown below…

Here is the Scene Hierarchy of the dialog…

The UI_Exit is an empty Game Object attached to the Canvas that has an Image as a child. And the buttons and text are all children of the Image. I have set it up this way as the script that controls all of this is hosted to the UI_Exit Game Object, so to Show/Hide the UI all I need to do is turn on/off the Image Game Object. Simples! Now for the code…
Code…
Add a new script to the UI_Exit Game Object called UI_Exit_Script and add the code below. The code here is super easy that an absolute novice in Unity/C# should be able to understand it relatively easily…
using UnityEngine;
using UnityEngine.UI;
public class UI_Exit_Script : MonoBehaviour
{
private bool _isShowing;
/// <summary>
/// Is the UI Showing
/// </summary>
public bool IsShowing
{
get { return _isShowing; }
set
{
_isShowing = value;
transform.Find("Image").gameObject.SetActive(_isShowing);
}
}
/// <summary>
///
/// </summary>
void Start()
{
// Add OnClick Listeners to buttons...
transform.Find("Image").Find("btn_Cancel").GetComponent<Button>().onClick.AddListener(HideUI);
transform.Find("Image").Find("btn_OK").GetComponent<Button>().onClick.AddListener(QuitApp);
HideUI();
}
/// <summary>
/// Code executed each update cycle.
/// </summary>
void Update()
{
// If the UI is not showing, then if user hits escape, show the UI...
if (!IsShowing)
{
if (Input.GetKeyDown(KeyCode.Escape))
{
IsShowing = true;
}
}
// If the UI is showing...
else
{
// If user hits escape then hide UI...
if (Input.GetKeyDown(KeyCode.Escape))
{
HideUI();
}
// If the user hits enter, then quit application...
if (Input.GetKeyDown(KeyCode.KeypadEnter) || Input.GetKeyDown(KeyCode.Return))
{
QuitApp();
}
}
}
/// <summary>
/// Hides the UI.
/// </summary>
void HideUI()
{
IsShowing = false;
}
/// <summary>
/// Quit the Application.
/// </summary>
void QuitApp()
{
Debug.Log("Quitting application...");
IsShowing = false;
Application.Quit();
}
}
And that’s it. When you hit Escape, the dialog will pop up. When the dialog is showing, if you hit escape again the dialog will hide or if you hit enter the App will quit (or by using the Cancel and OK buttons respectively).
Hope you found this useful (this is my contribution to the 4 trillion similar examples of how to do this) and of course, thanks for reading! 🙂
Leave a Reply