- Home /
Help Saving Max Health With PlayerPrefs
I've been working on a simple upgrade system where the player has to collect 100 coins, and every time a hundred is collected, the player's health is upgraded. I have tried many, many ways to save the maxHealth var using playerprefs. Maybe someone has an answer for me, that would be much appreciated.
Here is some snippets of the Health script:
var curHealth = 3;
static var coins = 0;
static var maxHealth = 3;
coins = PlayerPrefs.GetInt("Coin");
function Start(){
curHealth = maxHealth;
}
function FixedUpdate(){
if(curHealth <= 0){
Application.LoadLevel(Application.loadedLevel);
}
if(coins == 100){
maxHealth ++;
curHealth = maxHealth;
coins = 0;
}
if(maxHealth > 10){
maxHealth = 10;
curHealth = maxHealth;
}
}
function OnTriggerEnter(other : Collider){
if(other.gameObject.tag == "Health"){
Destroy(other.gameObject);
curHealth = maxHealth;
}
if(other.gameObject.tag == "Coin"){
coins ++;
Destroy(other.gameObject);
PlayerPrefs.SetInt("Coin",coins);
}
}
Answer by Garrafote · Sep 08, 2013 at 01:24 AM
I'm not used to javascript but this is what i would do:
#pragma strict
var curHealth : int;
var coins : int;
var maxHealth : int;
function Awake() {
// setup playerprefs vars on awake
coins = PlayerPrefs.GetInt("Coin", 0);
maxHealth = PlayerPrefs.GetInt("MaxHealth", 3);
}
function Start(){
curHealth = maxHealth;
}
function FixedUpdate(){
if(curHealth <= 0){
Application.LoadLevel(Application.loadedLevel);
}
if(coins == 100){
maxHealth ++;
curHealth = maxHealth;
coins = 0;
// update playerpref vars every time the value change
PlayerPrefs.SetInt("Coin",coins);
PlayerPrefs.SetInt("MaxHealth",maxHealth);
}
if(maxHealth > 10){
maxHealth = 10;
curHealth = maxHealth;
// update playerpref vars every time the value change
PlayerPrefs.SetInt("MaxHealth",maxHealth);
}
}
function OnTriggerEnter(other : Collider){
if(other.gameObject.tag == "Health"){
Destroy(other.gameObject);
curHealth = maxHealth;
}
if(other.gameObject.tag == "Coin"){
coins ++;
Destroy(other.gameObject);
// update playerpref vars every time the value change
PlayerPrefs.SetInt("Coin",coins);
}
}
Is that wat you want?
Well I'll be damned. It's exactly what I needed. I've been working on this for weeks and the answer was that simple. Well, thank you. There was some code that's really not needed like line 27 and the coins pref outside the functions. And hey, you even set up my maxHealth limit like I was!
This is exactly what I needed. Thanks!
On second thought, there's a little problem. When I reload the level (Application.LoadLevel) or when I go to the main menu and press continue, the maxHealth increments by one. I don't want that. Where's the problem there?
Never$$anonymous$$d the last post. I guess those lines were needed.
Thank you, you're a genius.
Im glad I could help you @Cooper37!
Can you please help the community by accepting the answer?
Hey is there a way you can convert this to c# please and thank you! :)