- Home /
Saving Life And Updating in Game
Hi everyone, Im running into a slight problem. Im able to save lives when the game is over or when you are returning to the main menu but when I start the game the lives that were save do not update. But start at 20 again. I know it has to do with the Start being incorrect but I don't know how to have the Updated lives show instead of the Start lives. I want to show current lives that has been loss or gained. Any suggestions?
GameController.cs
//This is were I want to start off the game with Up-To_Date lives
void Start(){
life = 20;
SavingLives ();
}
//This is where I am saving the lives
public void SavingLives()
{
if (life >=0) {
PlayerPrefs.SetInt("life", life );
PlayerPrefs.Save();
}
}
MenuContoller.cs //This calls the saved lives to the main menu and saves and displays the current lives.
void Start () {
lifeUpdateText.enabled = true;
}
void Awake(){
lifeUpdateText.text = PlayerPrefs.GetInt ("life").ToString ("");
}
Answer by LSPressWorks · Apr 01, 2015 at 02:21 PM
Yeppers, it is the start function. Set a playerprefs value of newfile or something. If that is false then set the life to 20, otherwise load the life up.
You also need to store the life value in an variable after loading, instead of just putting it into a string.
localLife = PlayerPrefs.GetInt;
lifeUpdateText.text =localLife.ToString ("");
Stepping into your code, you're setting life to 20. Then saving that value to the file, overwriting the previous data. Then you are displaying the life.
in pseudoCode
if(file IS_NEW) then SET_LIFE == 20 and set file to NOT_NEW
else GET_LIFE and place into a variable
DISPLAY_LIFE on updateText.text
if(PLAYER_DEAD or QUIT_GAME) then SET_LIFE.
Im a bit confused with the pseudoCode, I believe I got it but I don't think I'm looking at it right. So I should make IS_NEW a bool and set it to true saying that if the game is new set the lives to 20 Right? How is the game suppose to know if it's new, I'm confused on setting this up sorry about that.
Still can anyone help me I am still lost here. Please help?
Answer by Priyanka-Rajwanshi · Apr 01, 2020 at 10:56 AM
You have been resetting life = 20; in the Start. Instead, it is advised to use the following in the Start function:
life = PlayerPrefs.GetInt("life", 20);
This way, whatever life count is last saved, the same is used again in the start function. Moreover, if you want to replenish lives after sometime, you can check out the following link: http://codesaying.com/life-counter-in-unity/