Hi! I am brand new to Unity, or coding at all (other than HTML). I am making a menu for the roll a ball tutorial, and everything works except the quit button. I am following Recorded Video Sessions on UI - Unity Learn to create the menu, but changing the bottom button to quit the game. I am using this code that does not work (C#):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Quitscript : MonoBehaviour
{
void QuitGame()
{
Application.Quit();
Debug.Log("Game is exiting");
}
}
in the âOn Click ()â window i have put the Quitscript in the bottom, but i read that i donât need to add anything in the function part. Is this correct?
Thanks! But when i continued wathcing the guide he added a quit button that also works when in the editor. Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QuitOnClick : MonoBehaviour {
public void Quit ()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit ();
#endif
}
}
If anyoneâs still wondering what the solution is, thereâs nothing wrong with the code, that works fine. But you need to make an empty game object and put the quit script onto that by itself.
And then in the OnClick part of the button, put the game object that has the script attached to it.
After that, you should be able to click the âno functionâ part and find what youâre looking for.
(The name of your script, and then the name of the void function. Example: QuitScript â QuitGame() then it should work.)
I think your problem was that you were putting the script straight from your ProjectFolders in the OnClick, instead of a game object.
(This also works for restart scripts, and I think scripts in general when youâre trying to attach them to the OnClick).
I donât know why other people have struggled to get your code to work, I tried it and it worked first time perfectly. Itâs a really simple solution so I guess the people complaining must have done something wrong or missed something out.
Personally I say thank you as this really helped me out and finished off my game nicely!
Iâve just said that I think your solution works perfectly, it did for me anyway so I have no idea why some people have posted negative comments. I wanted to say thank you for helping as this finished my game nicely.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class QuitGame : MonoBehaviour
{
public void QuitTheGame() {
Application.Quit();
}
}
I couldnât understand why some people werenât able to get this working as it worked perfectly for me. The only difference was that I added the âpublicâ keyword before âvoidâ when writing my function. Like you I assigned the script to an object which in my case was the button I used to trigger the Application.Quit(); function call.