Search code examples
c#unityscriptunity-game-engine

UI Canvas Start - Quit Game


I have 2 Canvas UIs (Start and Exit) on the home screen of my game. I want to add 1 script that does the following:

When the UI Image Play is clicked

public void NextLevel(int level)
{
    Score.Inicializar(); 
    Application.LoadLevel (1);

}

When the UI Image Exit is clicked

Application.Quit ();

C# if possible.


Solution

  • Add this script to your Play image:

    using UnityEngine;
    using UnityEngine.EventSystems;
    //using UnityEngine.SceneManagement; // uncomment this line in case you wanna use SceneManager
    
    public class HandleClickOnPlayImage : MonoBehaviour, IPointerClickHandler {
        int level = 1; // I'm assuming you're setting this value somehow in your application
    
        public void OnPointerClick (PointerEventData eventData)
        {
            Score.Inicializar(); 
            Application.LoadLevel (level);
            // SceneManager.LoadScene (level); // <-- use this method instead for loading scenes
        }   
    }
    

    And add this script to your Exit image:

    using UnityEngine;
    using UnityEngine.EventSystems;
    
    public class HandleClickOnExitImage : MonoBehaviour, IPointerClickHandler {
        public void OnPointerClick (PointerEventData eventData)
        {
            Application.Quit();
        }   
    }
    

    And finally make sure no other ui blocking/overlapping your images, otherwise they won't receive any click event.

    Not to mention that a script file's name should match the name of it class :)