- Home /
Event System, OnClick function
Hi, I'va a problem to change scene upon clicking the button. I use countdown so when user click all the button before the timer end, it will pop out congrats message. And if the timer end before doing so, 'game over' message will pop out. By the way, I'm new to Unity. Hope you guys can help me to sort it out. Thanks in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class StartDown : MonoBehaviour
{
int countDownStartValue = 20;
public Text timerUI;
public GameObject gameOver;
public GameObject Menu;
public GameObject ViewCreature;
public GameObject Exit;
public GameObject wonM;
public bool won = false;
public Button Trash1;
public Button Trash2;
public Button Trash3;
public Button Trash4;
void Start()
{
countDownTimer();
gameOver.SetActive(false);
Menu.SetActive(false);
ViewCreature.SetActive(false);
Exit.SetActive(false);
wonM.SetActive(false);
Trash1.onClick.AddListener(TaskOnClick);
Trash2.onClick.AddListener(TaskOnClick);
Trash3.onClick.AddListener(TaskOnClick);
Trash4.onClick.AddListener(TaskOnClick);
}
public void TaskOnClick()
{
if (won)
{
won = true;
Menu.SetActive(true);
ViewCreature.SetActive(true);
Exit.SetActive(true);
wonM.SetActive(true);
}
else
{
gameOver.SetActive(true);
}
}
void countDownTimer()
{
if (countDownStartValue > -1)
{
timerUI.text = " " + countDownStartValue;
countDownStartValue--;
Invoke("countDownTimer", 1.0f);
}
else
{
gameOver.SetActive(true);
FindObjectOfType<Sound>().DeathSound();
Menu.SetActive(true);
ViewCreature.SetActive(true);
Exit.SetActive(true);
wonM.SetActive(false);
}
}
}
Answer by Llama_w_2Ls · Jul 28, 2020 at 10:15 AM
Well you could have an int
called score increase by one every time you press any button. Then, you can compare your score by saying if (score >= winValue)
then output a win message, and move on to the next scene or next level by writing SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1)
. If the score you got is not enough, meaning you didnt click all the buttons if (score < winValue
then you can output a game over message and also reload the scene by typing SceneManager.LoadScene(SceneManager.GetActiveScene())
Hope it helps @d076696
Its important to add your scenes to the build settings window before you run your game!
Your answer
Follow this Question
Related Questions
Animation works only once on button click 4 Answers
Button OnClick() calling wrong function 1 Answer
Add different input for On Click event (UI) 0 Answers
OnClick() animation 0 Answers