- Home /
Can't re-enable a gameobject
Hello, I'm making a 2D platformer game and I'm using a game controller to deactivate and reactivate the UI depending on what scene the player is in. However, when I deactivate the UI, I can't reactivate it for some reason. Here's my code:
[SerializeField] private string sceneName;
private GameObject player;
private LevelLoader levelLoader;
[SerializeField] private GameObject UI;
private void Awake()
{
levelLoader = FindObjectOfType<LevelLoader>();
player = GameObject.FindGameObjectWithTag("Player");
UI = GameObject.FindGameObjectWithTag("UI");
}
private void Start()
{
switch (SceneManager.GetActiveScene().name)
{
case "Leaderboard":
Destroy(player);
UI.SetActive(false);
break;
case "End":
Destroy(player);
UI.SetActive(false);
break;
case "LevelSelect":
UI.SetActive(false);
Debug.Log("In level select case");
break;
default:
UI.SetActive(true);
//UIController.instance.enabled = true;
break;
}
}
void Update()
{
switch (SceneManager.GetActiveScene().name)
{
case "Leaderboard":
Destroy(player);
UI.SetActive(false);
break;
case "End":
Destroy(player);
UI.SetActive(false);
break;
case "LevelSelect":
UI.SetActive(false);
Debug.Log("In level select case");
break;
default:
UI.SetActive(true);
break;
}
if (PlayerHealth.instance.currentLives <= 0)
{
levelLoader.LoadNextLevel(sceneName);
}
}
I don't understand why it's saying the gameObject has been destroyed if I just deactivated it. I appreciate any help and thank you in advance.
Answer by kaancetinkayasf · May 09 at 02:53 PM
When you disable the gameobject like you do, you can't enable it again. Because if your script is part of the object being disabled, the script is also disabled.
What you can do is, create a root object and make your actual gameobject child of it. But attach the script to the root game object. Run through the children of the root gameobject and then disable all children
Thank you, that worked! However, what I don't understand is that I was already doing that with a gameObject that wasn't the parent. This script above was on a GameController that I was going to use to activate and deactivate the UI, but I just did it on the parent of the UI components I had.