The question is answered, right answer was accepted
HP not being Set for Enemy class
Hey there, I'm a bit in a conundrum, did a few Debuggings tries and just can't find the issue. The following script is supposed to set the current health to max health on initialisation. But when I run the script and try to hit the enemy once, the "curHealth" is set to 0 at any given point of time, and thus get's killed with one hit. Does anybody have a clue what could be the issue/bug I have been overlooking the entire time?
public class Enemy : MonoBehaviour {
[System.Serializable]
public class EnemyStats
{
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 EnemyStats stats = new EnemyStats();
public void DamageEnemy(int damage)
{
Debug.Log("I have " + stats.curHealth + " HP.");
stats.curHealth -= damage;
if (stats.curHealth <= 0)
{
Debug.Log("Killing Enemy!");
//GameMaster.KillEnemy(this);
}
}
}
Many thanks.
Best Regards Koda
You seem to never call Init
so the value of curHealth
stays at 0. $$anonymous$$oreover, are you sure maxHealth
is greater than 0?
maxHealth is set inside unity as 100. Sorry, should have mentioned that. Where should I call the Init function then? Or should I turn the Init into Awake/Start function?
Answer by Kodaigan · May 14, 2018 at 09:05 AM
After experimenting around,this script get's fixed if Init
is replaced by Awake
and the function taken out of the EnemyStats class function. Which corresponds to Hellium's comment that Init
never get's called. The script will look like this now:
[System.Serializable]
public class EnemyStats
{
public int maxHealth = 100;
private int _curHealth;
public int curHealth
{
get { return _curHealth; }
set { _curHealth = Mathf.Clamp(value, 0, maxHealth); }
}
}
public void Awake()
{
stats.curHealth = stats.maxHealth;
}
public EnemyStats stats = new EnemyStats();
public void DamageEnemy(int damage)
{
Debug.Log("I have " + stats.curHealth + " HP.");
stats.curHealth -= damage;
if (stats.curHealth <= 0)
{
Debug.Log("Killing Enemy!");
//GameMaster.KillEnemy(this);
}
}
I would advise to keep the Init
function and just call it in the Awake
function of your $$anonymous$$onoBehaviour
.
I realized that in the end, that it didn't matter where the function was. I was a bit...inexperienced when I realized that I could've fixed it by calling it in either an Awake function outside of the EnemyStats
class. or a Start function. Preferebly in Awake function. So yeah. I kinda re-refixed it. Thanks for the help though!