- Home /
Don't lose variable data when reloading a level - c#
Hi, In my game when I used Respawn() I want it to obviously respawn the player, however I want it to save the amount of lives and score the player has when the level is reloaded. When the player does die it reloads the level but the live remain on 3.
public int lives = 3;
void Respawn()
{
lives -= 1;
DontDestroyOnLoad (gameObject);
Livestext (); //ignore
Application.LoadLevel(Application.loadedLevel);
}
As you can see I tried DontDestroyOnLoad but I still had the same results...
Thanks in advance.
Answer by kingcoyote · Sep 07, 2015 at 07:02 PM
You can store permanent data using PlayerPrefs. When the game first starts, call
PlayerPrefs.SetInt("lives", 3);
And on death call
PlayerPrefs.SetInt("lives", PlayerPrefs.GetInt("lives")-1);
I tried that but I got the same results @kingcoyote
Here's my full code:
void Start()
{
PlayerPrefs.SetInt ("lives", 3);
PlayerPrefs.SetInt ("score", 0);
ScoreText ();
Livestext ();
winText.text = "";
loseText.text = "";
}
void Respawn()
{
PlayerPrefs.SetInt ("lives", PlayerPrefs.GetInt ("lives") - 1);
DontDestroyOnLoad (transform.gameObject);
Livestext ();
Application.LoadLevel(Application.loadedLevel);
}
Answer by cjdev · Sep 07, 2015 at 10:11 PM
Try using it this way:
void Awake() {
DontDestroyOnLoad(transform.gameObject);
}
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
Play different music depending on the current scene 2 Answers
C# Respawn Help 1 Answer