- Home /
Health script, save health in between scenes. PlayerPrefs.
Hi I have made a simple health script, using Unity's GUI to create a health bar which decreases as you loose health. I've also added a button which makes you loose 10 health each time you press it.
Now I'm trying to script so that your current health stays the way it was last scene, when you change scene. I have tried using PlayerPrefs, and it does work since the current health is the same when you change scene. Though if you quit the game and re-enter you still have the same amount of hp you had last time you played. I want it to go back to maximum health at every start-up, though not when the next scene starts.
using UnityEngine; using System.Collections;
public class healthScript : MonoBehaviour {
public int maxHealth = 100; // Minimum health is 0.0f (dead)
public int currentHealth = 100; // Players current health
public float healthBarLenght;
public Texture healthBartexture;
void Awake (){
PlayerPrefs.SetInt("healthP",maxHealth);
}
// Use this for initialization
void Start () {
currentHealth = PlayerPrefs.GetInt("healthP");
healthBarLenght = Screen.width / 2;
}
// Update is called once per frame
void Update () {
adjustCurrentHealth(0);
if(Input.GetKeyDown(KeyCode.O))
{
currentHealth = currentHealth - 10;
SaveHealth();
}
}
void OnGUI (){
GUI.Box(new Rect(10, 10, healthBarLenght, 20), currentHealth + "/" + maxHealth);
if (currentHealth == 0)
{
GUI.Box(new Rect(0,0,Screen.width,Screen.height), "Game Over");
Time.timeScale = 0.0f;
}
}
public void adjustCurrentHealth(int adj)
{
currentHealth += adj;
if (currentHealth < 0)
{
currentHealth = 0;
}
if (currentHealth > maxHealth)
{
currentHealth = maxHealth;
}
if (maxHealth < 1)
{
maxHealth = 1;
}
healthBarLenght = (Screen.width / 2) * (currentHealth / (float)maxHealth);
}
void SaveHealth (){
PlayerPrefs.SetInt("healthP",currentHealth);
}
}
Answer by save · Oct 25, 2011 at 06:09 PM
Protect it by using DontDestroyOnLoad() between scenes. Only save health when saving the state of progress.
Answer by green_core · Oct 26, 2011 at 08:09 AM
Also you can just use static variable to save health.
change
public int maxHealth = 100;
to
static int maxHealth = 100;
think of static variables as "global". 1 variable affects all instances of an object / member. Therefore, it makes sense that there can only be 1 instance of the variable.
Your answer
Follow this Question
Related Questions
I'm trying to set a high score but I can't display it in another scene? 2 Answers
How Do You Have Multiple High Scores For 1 GameOverScene? 1 Answer
Slider won't slide, issue assigning PlayerPrefs and then changing the PlayerPrefs' value 1 Answer
How to write If the player don't play the game for 24 hours, the game is over. 1 Answer