- Home /
Variable in a DontDestroyOnLoad class resetting.
Hello, I haven't been able to find a specific answer for this.
I have a class with DontDestroyOnLoad, and when I "restart" the level, a variable in that class resets.
public class ScoreController : MonoBehaviour {
public static ScoreController score;
public GameObject hs;
public float points;
public float highscore;
void Awake () {
if (score == null) {
DontDestroyOnLoad (gameObject);
score = this;
} else if (score != this) {
Destroy (gameObject);
}
}
void Start()
{
score.points = -10;
}
// Update is called once per frame
void Update () {
GetComponent<Text> ().text = "Score: " + points;
hs.GetComponent<Text>().text = "Highscore: " + highscore;
}
}
I want "highscore" to persist when I reload the level but it's resets to 0. Anyone knows why? I know I can use PlayerPrefs or even load a binary file but I wanted to use this approach.
I call highscore like this ScoreController.score.highscore I don't know if that could be a problem.
Couldn't spot any issues, so I ran your code and it works fine. I'm guessing this is something not in this script that's modifying highscore.
I don't initialize it in any script, and it has the correct value before the level load, the only thing that's left is that the inspector is resetting it. This script is on a UI Text, child of a Canvas in the Hierarchy.
Try setting it private and see it is compiles or breaks.
I already solved it but the answer is waiting for moderator. It was the hierarchy, more details in the answer.
Answer by Mbastias · Jan 01, 2015 at 01:42 AM
Ok, it was the Hierarchy. This script was in a UI Text, and that Text was a child of a Canvas. So, I suppose that when the level loaded the Canvas was destroyed and therefore it childs and the Text that had the script.
To solve it, I moved the script to the Canvas, so now the Canvas is persistent, and added a public GameObject that has the points Text. Now is working as intended. Thanks @RudyTheDev for your interest.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Setting public GameObject to a different Prefab through code 0 Answers