Quitting game by pressing esc/escape key

There’s some tutorials and posts covering this but i find them all confusing, because i don’t know how to enable the script or where to put it.

I’m really new to this kinda stuff, i’d really appreciate it if someone would help me i need to have this school project done by tomorrow. :c

stick this on an empty object in the scene.

the update method runs every update, checks to see if the user pressed down the escape key, if so it call Application.Quit which quits the game.

it’s kida suedo so you’re gonna have to fix typos

public class GameManager : MonoDevelop {

void Update(){

if(Input.GetKeyDown(escape))
Application.Quit();

}

}

i always get “Can’t add script”, it says The script needs to derive from MonoBehaviour

SparrowsNest made a couple mistakes in his script. The error you get now is because he said MonoDevelop instead of MonoBehaviour.

This script is in the official docs:

using UnityEngine;
using System.Collections;

// Quits the player when the user hits escape

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey("escape"))
        {
            Application.Quit();
        }
    }
}

This can be attached to ANY object in the scene. Camera, light, ground object, your character, an Empty, whatever. You just need one. This is because every active object in the scene will have all of its Update() functions called.

4 Likes

I’m still getting the error :d

Make sure the class name and the file name match exactly.

I have no idea what you’re saying, i think this might be the issue then. Whats class name?

1 Like

In the official script I posted, they called the class ExampleClass. This means it should be in a file called ExampleClass.cs and added to an object.

Is your error message about GameManager or ExampleClass?

Matching names allowed me to add script, tested game after build and it works now. Thanks for hand all c: i didn’t expect to get answers this quick.

The script doesn’t work for me. I get no errors, but nothing happens.

2 Likes

Is it attached to a gameobject running in the scene?

Yes, its attached to a empty gameobject in the scene.

Add Debug.Log statements everywhere to figure out what path the code is taking.

This video shows how to quit a Unity game or app by clicking a button or pressing keys on the keyboard.

i hope this helps your question here (i just realized the date was long time ago lol)

if (Input.GeyKey(KeyCode.Escape)) //Get the Esc / Escape key via the keycode enum
            Application.Quit(); //Quit the game lol

um does any of this still work?

Your code does not make my game exit

Please don’t necro post. Make your own post, and remember: we cannot read your mind.

When you make a new post, here is how to report your problem productively in the Unity3D forums:

http://plbm.com/?p=220

This is the bare minimum of information to report:

  • what you want
  • what you tried
  • what you expected to happen
  • what actually happened, especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

How to do tutorials properly, two (2) simple steps to success:

Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That’s how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.
Fortunately this is the easiest part to get right: Be a robot. Don’t make any mistakes.
BE PERFECT IN EVERYTHING YOU DO HERE!!

If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there’s an error, you will NEVER be the first guy to find it.

Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

It’s true Unity’s documentation needs to be updated, for multiple reasons. Application.Quit() does not work in the Editor anymore, and if you’re using the new Input System it’s kind of a hassle to poll for specific keys.

Here’s a more full-featured version of the script, which I use during development. Also, since the usual Pause shortcut disappears if you turn off Unity Shortcuts in Play Mode, I added it back with an F12 poll.

// QuitAppOnEscape.cs
//
using UnityEngine;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif

namespace halley
{
    //
    // Throw this on any always-present game object such as Main Camera
    // in any generic super-simple apps for deployment on Android or
    // Standalone.
    //
    // Unity has two input handling setups.
    //  - the "legacy" Input handling setup
    //  - the "new" InputSystem handling setup
    //
    // This class uses the new InputSystem if it has been enabled.
    //
    // Project Settings >
    //    Player >
    //       Other Settings >
    //          Configuration >
    //             Active Input Handling = Both
    //
    public class QuitAppOnEscape: MonoBehaviour
    {
        [Tooltip("If true, Quit works in built apps outside editor too.")]
        public bool standalone = false;

        void Awake()
        {
#if UNITY_EDITOR
            if (!standalone)
                if (UnityEditor.EditorApplication.isPlaying)
                    Destroy(this);
#endif
        }

        void Update()
        {
#if ENABLE_INPUT_SYSTEM
            if (Keyboard.current.escapeKey.wasReleasedThisFrame)
#else
            if (Input.GetKeyUp("escape"))
#endif
            {
                Debug.Log($"Quitting App on Escape Key struck.");
                Quit();
            }

#if ENABLE_INPUT_SYSTEM
            if (Keyboard.current.f12Key.wasReleasedThisFrame)
#else
            if (Input.GetKeyUp("f12"))
#endif
            {
                Debug.Log($"Pausing Game on F12 Key struck.");
                Pause();
            }

        }

        void Pause()
        {
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPaused = true;
#endif
        }

        void Quit()
        {
#if UNITY_EDITOR
            // Application.Quit() does not work in the editor so
            // UnityEditor.EditorApplication.isPlaying need to be
            // set to false to end the game.
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
        }
    }
}
1 Like