- Home /
Help with HealthBar script.
When my player hit a rock with their raft theplayer looses 1 point of health and the scene begins again. I'm using player prefs to forward the player health to the next scene. I don't think it si working. Wneh game over is declared by my script how do I reset Health back to 3 when the player wants to start another game. I've attached the script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Healthbar: MonoBehaviour {
//private GameController gameController;
private float health = 3;
public Slider slider;
public Text text;
void Start ()
{
health = PlayerPrefs.GetFloat ("health");
//health = 3;
}
void Update()
{
slider.value = health; //syncing value of slider with player health
text.text ="Health : " + health; //syncing text with player health
}
//Function which detects collision
void OnTriggerEnter(Collider other)
{
//checking whether object tagged Enemy is collided
if (GameObject.FindWithTag ("Hazards"))
{
health = health - 1;
PlayerPrefs.SetFloat("health", health);
SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex);
if(health <= 0)
{
Debug.Log("Game Over");
}
}
}
}
Answer by tormentoarmagedoom · Jan 30, 2019 at 04:04 PM
Good day.
Do not use PlayerPRefs for this! Never!
I strongly recommend you toi watch this official tutorial
https://unity3d.com/es/learn/tutorials/topics/scripting/persistence-saving-and-loading-data
It's 100% necessary to know, at least how to use the DontDestroyOnLoad, in order to keep information from scene to scene. (Player prefs can be used to save data when you close the game, but its not for this and even less to transfer data from scene to scene!)
Good luck!