Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

I am having an issue where the code below just will not work. I don't know the problem

Discussion in 'Scripting' started by GameDev1203, Jul 17, 2022.

  1. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    using UnityEngine;
    public class Credits : MonoBehaviour
    {
    public void QuitTheGame()
    {
    Debug.Log("Quit Game");
    Application.Quit();
    }
    }
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,457
    1. Use code blocks (check pinned threads)
    2. Always explain what doesn't work. So give more detail on what it does do, what it should do, if the log gets called and where/how you call this function
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,964
    Did you read the docs to learn how Application.Quit() does nothing in the editor?

    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!!!)

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    You must find a way to get the information you need in order to reason about what the problem is.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as
    Debug.Log("Problem!",this);


    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494
     
  4. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    @GameDev1203 here is my `Main.cs` file, just attach to an empty game object named "Main" without the quotes, note { the name of the Game Object does NOT matter, it's just easier to do it this way }, move the Game Object out of the way once the script is attached, enter the game in either play mode or compiled mode, and away you go :

    Main.cs :
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Threading.Tasks;
    5. using UnityEngine;
    6.  
    7. public class Main : MonoBehaviour {
    8.  
    9.     [HideInInspector]
    10.     public bool useKillAppKey=true;
    11.  
    12.     [HideInInspector]
    13.     public static bool killApp=false;
    14.  
    15.     [HideInInspector]
    16.     public bool preventAppQuit;
    17.  
    18.     [HideInInspector]
    19.     public float killAppWaitTime=3.0f; // <---- Set to `0` for INSTANT quit
    20.                                        //       without wait time
    21.  
    22.     public bool WantsToQuit(){
    23.         return ! preventAppQuit;
    24.     }
    25.  
    26.     /// <summary>
    27.     /// Wait for x seconds and invoke the given callback
    28.     /// </summary>
    29.     public static async void Wait(float seconds, Action onWaitFinished=null){
    30.         // Delay this asynchronous method for `x` time in `seconds` | { WILL NOT BLOCK MAIN THREAD }
    31.         await Task.Delay(TimeSpan.FromSeconds(seconds));
    32.         onWaitFinished?.Invoke();
    33.     }
    34.  
    35.     public static bool KillApp(float seconds=0.0f, bool useDebug=false){
    36.         #if UNITY_EDITOR || UNITY_EDITOR_64 || UNITY_EDITOR_WIN || UNITY
    37.             if (UnityEditor.EditorApplication.isPlaying==true){
    38.                 killApp=true;
    39.                 Time.timeScale=0;
    40.                 Wait(seconds, ()=>{UnityEditor.EditorApplication.isPlaying=false;});
    41.             }
    42.         #else
    43.             if (seconds>0.0f){
    44.                 killApp=true;
    45.                 Time.timeScale=0;
    46.                 Wait(seconds, ()=>{Application.Quit();});
    47.             }
    48.             else{
    49.                 killApp=true;
    50.                 Application.Quit();
    51.             }
    52.         #endif
    53.         if (useDebug==true){Debug.Log($"killApp:{killApp}");}
    54.         return killApp;
    55.     }
    56.  
    57.     private void Start(){
    58.         Application.wantsToQuit+=WantsToQuit;
    59.     }
    60.  
    61.     private void Update(){
    62.         #if UNITY_EDITOR || UNITY_EDITOR_64 || UNITY_EDITOR_WIN || UNITY
    63.             if (Input.GetKey(KeyCode.Escape)){ killApp=KillApp(killAppWaitTime); }
    64.         #else
    65.             if (Input.GetKey(KeyCode.Escape)){ killApp=KillApp(killAppWaitTime); }
    66.         #endif
    67.     }
    68.  
    69. }
    Also note, I will add some extra stuff on to it and put it in the app store if you're interested, it will only be $5.00 when it is fully debugged, some features added and compiled. I will also release this version as a free source code + project in the app store This is the basic framework I created, feel free to use it. You do not have to credit me if you don't want to but it would be thoughtful and kind. Also, please keep the header at the top of the script in at all times. That is all I ask. Other than that, have fun and good luck with your game !!!
     
    Last edited: Jul 18, 2022
  5. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    @Kurt-Dekker
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Credits : MonoBehaviour
    4. {
    5.  
    6.     public void QuitTheGame()
    7.     {
    8.         Debug.Log("Quit Game");
    9.         Application.Quit();
    10.     }
    11.  
    12. }
    13.  


    The Debug.Log statement was to show me if the Application.Quit would work by posting in the console.
    Desktop Screenshot 2022.07.17 - 19.05.34.50.png

    - what I want-My game to quit one its exported but for now post Quit Game in the console
    - what I tried- using unity's clean up, changing to public object, moving the code to being a component of the button I was using
    - what I expected to happen- Quit Game to be posted in the console
    - what actually happened, especially any errors you see- nothing happened when I clicked the button and I have no reported errors
    - links

    I'm not sure if the image helps but I figured I would include it
     
  6. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,015
    Application.Quit() doesn't work when playing in the editor. What you need is to change the logic depending on whether you're in the editor or not.

    One such pattern is:
    Code (CSharp):
    1. public void QuitGame()
    2. {
    3. #if UNITY_EDITOR
    4.     UnityEditor.EditorApplication.isPlaying = false;
    5. #else
    6.     Application.Quit();
    7. #endif  
    8. }
     
  7. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    I posted a working example above that works with the editor and compiled and WebGL versions. Although in WebGL, it will only go to a black screen and stop the game from playing.
     
  8. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    I am building in windows not WebGL
     
  9. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    @GameDev1203 Did you not read what I said CAREFULLY? I said it ALSO works for WebGL as WELL as Windows. Not trying to sound "rude", just trying to help. :)
     
  10. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    Sorry I read it to fast
    so are you suggesting I use your code
     
  11. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    @GameDev1203 Try it. If you like it, use it. ^_^ So yes, I am saying that.
     
  12. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    What should I change Credits.QuitTheGame to
    in the on click event
     
  13. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    I am also having an issue with my start button
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.SceneManagement;
    3.  
    4. public class MenuScript : MonoBehaviour
    5. {
    6.     public void StartGame()
    7.     {
    8.         SceneManager.LoadScene("Level01");
    9.     }
    10.  
    11. }
    12.  
    13.  
    this is connected to a button and It should start my game but nothing is happening not even errors
     
  14. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    Just call my KillApp ( ) function when the button is hit, here's a modified version that will allow you to call the actual function instead of having to use the Escape key.

    Main.cs :
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System.Threading.Tasks;
    5. using UnityEngine;
    6.  
    7. public class Main : MonoBehaviour {
    8.  
    9.     [HideInInspector]
    10.     public bool useKillAppKey=true;
    11.  
    12.     [HideInInspector]
    13.     public static bool killApp=false;
    14.  
    15.     [HideInInspector]
    16.     public bool preventAppQuit;
    17.  
    18.     [HideInInspector]
    19.     public float killAppWaitTime=3.0f; // <---- Set to `0` for INSTANT quit
    20.                                        //       without wait time
    21.  
    22.     public bool WantsToQuit(){
    23.         return ! preventAppQuit;
    24.     }
    25.  
    26.     /// <summary>
    27.     /// Wait for x seconds and invoke the given callback
    28.     /// </summary>
    29.     public static async void Wait(float seconds, Action onWaitFinished=null){
    30.         // Delay this asynchronous method for `x` time in `seconds` | { WILL NOT BLOCK MAIN THREAD }
    31.         await Task.Delay(TimeSpan.FromSeconds(seconds));
    32.         onWaitFinished?.Invoke();
    33.     }
    34.  
    35.     public static bool KillApp(float seconds=0.0f, bool useDebug=false){
    36.         #if UNITY_EDITOR || UNITY_EDITOR_64 || UNITY_EDITOR_WIN || UNITY
    37.             if (UnityEditor.EditorApplication.isPlaying==true){
    38.                 killApp=true;
    39.                 Time.timeScale=0;
    40.                 Wait(seconds, ()=>{UnityEditor.EditorApplication.isPlaying=false;});
    41.             }
    42.         #else
    43.             if (seconds>0.0f){
    44.                 killApp=true;
    45.                 Time.timeScale=0;
    46.                 Wait(seconds, ()=>{Application.Quit();});
    47.             }
    48.             else{
    49.                 killApp=true;
    50.                 Application.Quit();
    51.             }
    52.         #endif
    53.         if (useDebug==true){Debug.Log($"killApp:{killApp}");}
    54.         return killApp;
    55.     }
    56.  
    57.     private void Start(){
    58.         Application.wantsToQuit+=WantsToQuit;
    59.     }
    60.  
    61. }
    As for your StartGame() function, it is fine. You just have to call StartGame() when the button is pressed.
     
    Last edited: Jul 18, 2022
  15. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    There is no Kill app function
     
  16. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    or start app
     
  17. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    @GameDev1203 : You should read my code much more closely. yes there is a KillApp() function in the code I wrote above :

    Code (CSharp):
    1. public static bool KillApp(float seconds=0.0f, bool useDebug=false){
    Please read for meaning whenever I post.
     
  18. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    As for your StartGame() function you just need to call that function when you click the button.
     
  19. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    i cant access it in the editor
     
  20. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    @GameDev1203 : Please be more clear. What do you mean by "I can't access it in the editor?", what is the "it" you are referring to?
     
    Last edited: Jul 18, 2022
  21. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,015
    Why not just use the simple and straight forward code I provided? You don't need something quite as complicated when in your early learning stages.
     
    Kurt-Dekker likes this.
  22. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    @spiney199 I would but does this work when attached to a button and if so what should the button function be
     
  23. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    6,015
    If you hook this up to the OnClick event of a UI Button, like you had at the start, it should work.
     
  24. GameDev1203

    GameDev1203

    Joined:
    Jan 27, 2022
    Posts:
    11
    I got some code to work thank you