How to write an efficient game exit code?

Hello,
In Android games we exit the game using a exit button or using the Android “Back” (Escape) button. The following code exits a game.

void Update ()
    {
        if (Input.GetKey(KeyCode.Escape))
        {
            Application.Quit();
        }
    }

But isn’t it looking inefficient? Because, I am checking for “Back” button press 60 times/second (as it is inside Update function). Also, if want to change scenes, I have to do the same. Is there any other way that is more efficient?

That is just a simple boolean check. You do understand how many complex calculations Unity is doing behind the scenes to display your game right? Every frame.

One boolean check is absolutely nothing.

If you dont check input every frame there is a chance that you will miss the user pressing the key.

2 Likes

Thank you for your reply. Yes, I do understand. Just wondering that if Android has any default callback for the Back Button Pressing. :slight_smile:

1 Like

I guess behind the scenes the Unity player on android is hooking into the back button event. You could do sonething in a native plugin possibly?

It might end up costing more then the bool check.

Unity is Update driven through the game loop, rather then event driven. There are no default callbacks or events for input.

1 Like