- Home /
Unable to close the Game Over's panel after clicked a button
I am unable to close the Game Over's panel after clicked a button. In Resume()
I use gameOver.gameObject.SetActive(false);
but to no avail. Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HeartFYP : MonoBehaviour
{
public GameObject heart1, heart2, heart3, gameOver;
public static int health;
public Button gameOverReplayButton;
// Start is called before the first frame update
void Start()
{
health = 3;
heart1.gameObject.SetActive(true);
heart2.gameObject.SetActive(true);
heart3.gameObject.SetActive(true);
gameOver.gameObject.SetActive(false);
lifeBuy.isLifeSold = PlayerPrefs.GetInt("IsLifeSold");
gameOverReplayButton.interactable = false;
}
// Update is called once per frame
void Update()
{
if (health > 3)
health = 3;
switch (health)
{
case 3:
heart1.gameObject.SetActive(true);
heart2.gameObject.SetActive(true);
heart3.gameObject.SetActive(true);
break;
case 2:
heart1.gameObject.SetActive(true);
heart2.gameObject.SetActive(true);
heart3.gameObject.SetActive(false);
break;
case 1:
heart1.gameObject.SetActive(true);
heart2.gameObject.SetActive(false);
heart3.gameObject.SetActive(false);
break;
case 0:
heart1.gameObject.SetActive(false);
heart2.gameObject.SetActive(false);
heart3.gameObject.SetActive(false);
//FindObjectOfType<AudioManager>().PlaySound("GameOver");
gameOver.gameObject.SetActive(true);
Time.timeScale = 0;
break;
}
{
lifeBuy.isLifeSold = PlayerPrefs.GetInt("IsLifeSold");
if (PlayerPrefs.GetInt("IsLifeSold", lifeBuy.lifeTotalQuantity) == 0)
{
gameOverReplayButton.interactable = false; //disable button
}
else
{
gameOverReplayButton.interactable = true; //enable button
}
}
}
public void yesButton()
{
Resume();
lifeBuy.lifeTotalQuantity = PlayerPrefs.GetInt("IsLifeSold") - 1;
PlayerPrefs.SetInt("IsLifeSold", lifeBuy.lifeTotalQuantity);
}
public void Resume()
{
gameOver.gameObject.SetActive(false);
Time.timeScale = 1f;
heart1.gameObject.SetActive(true);
heart2.gameObject.SetActive(false);
heart3.gameObject.SetActive(false);
Debug.Log("Close Panel...");
}
}
Answer by GDGames0302 · May 14, 2021 at 10:37 AM
Hi. Your mistake is the switch function in the Update function. That is executed every frame. When the player dies and the health variable is 0, in the switch function you activate that panel. When you click the Resume button, your panel is deactivated, but is immediately activated by the switch function. You probably have a separate script where you decrease the player's health if something happens. When you decrease the health in that script, set a bool to true. Then, execute this switch function in the Update only if that bool is true. Don't forget to set the bool to false in the switch function. I don't have time to write any code for you, but I just wanted to explain how you can achieve what you want. Of course, there are other ways too. Hope it helps.