- Home /
C# Script issue with Player
Hello, am currently experiencing an issue with a life player system that I'm working on. It seems whenever the player dies, the number of lives goes from 3 to -87.
It should only take away one life when the player is killed by the enemy. I have tried putting the code in onGUI void instead of Update, however upon doing so it doesn't keep track of kills for the player and the lives stay the same. And when the code is placed in the Update void it goes from 3 to -87 for one kill.
The goal is when the player dies for his lives to subtract by -1 each time until ran out then it reloads the level.
Any help with this is greatly appreciated.
Code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Lives : MonoBehaviour {
public vp_FPPlayerDamageHandler player; //drag the actor into this variable in inspector
//Lives System
//private int lost = 1; //How much life should be lost when the player dies?
public static int curLives;
public int startinglives = 3; // How many Lives should the player start with?
public int lost;
//gui
public GUIStyle alive;
void Start()
{
curLives = startinglives; //Set the starting lives to default
}
void Update()
{
//If player dies, what's going on?
if (player.CurrentHealth <= 0) {
//If player dies, take away a life.
//curLives-=1;
Lives.curLives--;
}
else if (curLives == 0) {
//If all lifes are gone, reset the level
Application.LoadLevel(Application.loadedLevel);
}
}
void OnGUI()
{
GUI.Box (new Rect ((Screen.width)/20 -(Screen.width)/50,(Screen.height)/2-(Screen.height)/8,(Screen.width)/4,(Screen.height)/4), "Lives: " + curLives.ToString (),alive);
}
}
Answer by tanoshimi · Jun 06, 2015 at 08:27 PM
Well... in the first frame in which your player has zero or less CurrentHealth, their curLives gets reduced by one. Then, in the next frame, they have one less life, but their CurrentHealth remains the same, so they lose another life. The next frame? Lose a life. etc. etc.
I imagine that what you intended to do was that every time the player starts a new life, you restore their health. Something like:
if (player.CurrentHealth <= 0) {
Lives.curLives--;
player.CurrentHealth = 100; // or whatever your max health is
}