So I’m having a problem on something that should be extremely simple but there hasn’t been anything able to fix this, not even my programming teacher could see what’s wrong, wich makes me believe this is a problem related to unity, not my code.
I have a health system that works perfectly on enemies, and by using the same logic for the player health it simply doesn’t work, it’s like the int for the current health has two values at the same time, when I try to set it to the max health it doesn’t work at all, I tried in many different ways, but I can’t set it’s value at the beggining, wich means I start the game with the amount of health I had when I last stopped playing. But at the same time my player can die and it registers the damage somehow, but when I use Debug.Log to display my current health it only shows my maximum health (as if the current health was actually successfuly set to max when starting, but again it doesn’t matter because that’s not the real health, the real one is the amount I had last time I stopped playing) and when the player dies it suddently turns into zero, with nothing between max health and zero while I was taking damage, and this makes my health bar not work as intended as well.
Here’s the code:
public class PlayerHealth : MonoBehaviour
{
[System.Serializable]
public class PlayerStats
{
public int maxHealth;
private int _curHealth;
public int CurHealth
{
get { return _curHealth; }
set { _curHealth = Mathf.Clamp(value, 0, maxHealth); }
}
public void Init()
{
CurHealth = maxHealth;
}
}
public PlayerStats PStats = new PlayerStats();
private void Awake()
{
//I tried many ways to set the health at the beggining, didn't work with void start as well
PStats.Init();
}
public void DamagePlayer(int damage)
{
PStats.CurHealth -= damage;
if (PStats.CurHealth <= 0)
{
//this works ^^^
GameMaster.KillPlayer(this);
}
}
void Start()
{
//PStats.CurHealth = 100;
}
}