Problems with health system based on hearts
Hey there! I'm trying to make a simple thing: damage. I'm using a Hearts System for the Player Health like in Zelda games, but it keeps telling me that "Assets/Scripts/Working Scripts/HeartSystem.cs(63,17): error CS0266: Cannot implicitly convert type "float" to "int". An explicit conversion exists (are you missing a cast?)".
HeartSystem Script:
private int maxHeartAmount = 10;
public int startHearts = 3;
public int curHealth;
private int maxHealth;
private int healthPerHeart = 2;
public Image[] healthImages;
public Sprite[] healthSprites;
void Start () {
curHealth = startHearts * healthPerHeart;
maxHealth = maxHeartAmount * healthPerHeart;
checkHealthAmount ();
}
void checkHealthAmount () {
for (int i = 0; i < maxHeartAmount; i++) {
if (startHearts <= i) {
healthImages [i].enabled = false;
} else {
healthImages [i].enabled = true;
}
}
UpdateHearts ();
}
void UpdateHearts(){
bool empty = false;
int i = 0;
foreach (Image image in healthImages){
if (empty) {
image.sprite = healthSprites [0];
} else {
i++;
if (curHealth >= i * healthPerHeart) {
image.sprite = healthSprites [healthSprites.Length - 1];
} else {
int currentHeartHealth = (int)(healthPerHeart - (healthPerHeart * i - curHealth));
int healthPerImage = healthPerHeart / (healthSprites.Length - 1);
int imageIndex = currentHeartHealth / healthPerImage;
image.sprite = healthSprites [imageIndex];
empty = true;
}
}
}
}
public void TakeDamage(float amount){
curHealth -= amount;
curHealth = Mathf.Clamp (curHealth, 0, startHearts * healthPerHeart);
checkHealthAmount ();
}
public void AddHeartContainer(){
startHearts++;
startHearts = Mathf.Clamp (startHearts, 0, maxHeartAmount);
checkHealthAmount ();
}
Damage script:
float damage = -5f;
void OnTriggerEnter(Collider other){{
other.gameObject.GetComponent<HeartSystem> ().TakeDamage (damage);
}
}
Thx for the help :)
Answer by NoseKills · Jun 02, 2016 at 05:03 PM
Since you didn't attach all the text in the class the line number in the error isn't useful anymore. Double click the error in Unity console and it'll take you to the problematic line.
I think it's this line though curHealth -= amount;'.
'amount' is a float. If curHealth is 10 and you lose 0.1 health, do you want curHealth to drop to 9 or stay at 10? Your code needs to specify that. You either need to use floats for your health values and cast them to int when needed or vice versa.
After one hour thinking about what you said, finally managed to fix the code. Thank you :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612082107im_/https://answers.unity.com/themes/thub/images/avi.jpg)