- Home /
Scene Reload/Respawn system destroys UI
Sorry if this doesn't belong here; my first time posting!
Im working on little 2D RPG prototype for one of my classes and we decided we were going to add a respawn system that pops up a UI element that displays scores and a button the essentially calls a method to load the same scene again. Everything works on reload, except the UI element that popped up destroys itself, so that when you die again, everything is missing. It's all childed under our actual UI, which does stay on restart miraculously.
Here's pretty much everything that pertains to it:
void Start()
{
if (!UIExist)
{
UIExist = true;
DontDestroyOnLoad(transform.gameObject);
}
else
{
Destroy(gameObject);
}
playerStats = GetComponent<PlayerStats>();
scoreboard = new ArrayList();
scoreboard.Add(score1);
scoreboard.Add(score2);
scoreboard.Add(score3);
scoreboard.Add(score4);
scoreboard.Add(score5);
scoreboard.Add(score6);
scoreboard.Add(score7);
scoreboard.Add(score8);
scoreboard.Add(score9);
scoreboard.Add(score10);
deathScreen.SetActive(false);
screenHolder = deathScreen;
}
public void Reload()
{
playerHealth.hpCurrent = playerHealth.hpMax;
SceneManager.LoadScene("main");
screenHolder.SetActive(false);
playerHealth.gameObject.SetActive(true);
}
The screenholder gets set active elsewhere.
Answer by Anis1808 · Dec 03, 2019 at 11:54 PM
Use the very useful DontDestroyOnLoad(Object);
function. There is more info on the unity documentation. In brief, you have to add this line to your Start function on a script and add the script to whatever objects you want to keep when reloading the scene.
Answer by WhyDev · Dec 04, 2019 at 03:26 AM
I did exactly that and added to literally every object I could. Right now the only console error is MissingReferenceException: The object of type 'Text' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
What it's pointing at is:
public static void CreateLeaderboard(ArrayList scores)
{
int i = 0;
foreach(Text scoreBox in scoreboard)
{
if (scores.Count >= (i + 1))
{
scoreBox.text = scores[i].ToString(); <<<<<<<<<<<<<<<<<<<< This Line
i++;
}
else
{
scoreBox.text = "0";
}
}
screenHolder.SetActive(true);
}
Your answer
Follow this Question
Related Questions
Check the toggle status of other game objects from a script 0 Answers
Scripting button functionality inside class with created object's method 1 Answer
Function deleting string by itself. 0 Answers
How to create a lasting UI button that would set a game object to active . 0 Answers
UI Text showing weird string value? 1 Answer