Cannot convert float to int?
I have a mana system and a specific attack will drain this as the mouse button is held down. The lowest float I set it to (1) still drains it too fast. But I can't drop below that because I get the "cannot implicitly convert type" error. This is from the mana system script:
void Update()
{
manaValue.value = Mathf.Lerp(manaValue.value, (float)player.playerMana / (float)player.playerMaxMana, 0.5f);
}
And this is a separate script where I'm draining the mana and trying to use an int:
if (Input.GetMouseButton(0))
{
controller.playerMana = controller.playerMana - 0.5f;
}
What can I do to fix this?
Try using floats for player$$anonymous$$ana and player$$anonymous$$ax$$anonymous$$ana?
Answer by Cherno · Sep 23, 2015 at 09:23 PM
Mathf.Lerp returns a float so it's not wonder you get this error.
manaValue.value = (int)Mathf.Lerp(manaValue.value, (float)player.playerMana / (float)player.playerMaxMana, 0.5f);
or
manaValue.value = Mathf.RoundToInt(Mathf.Lerp(manaValue.value, (float)player.playerMana / (float)player.playerMaxMana, 0.5f));
However, I don't know if the lerping would actually change the manaValue when rounding the end result. A better way would be to make the manaValue a float and display it with Mathf.RoundToInt if you don't want decimals in your GUI. Generally speaking, if lerping and similar operations are involved, it's best to make the variable a float and not an int. If you really want to keep it as an int, you can also consider slowing the rate at which it decreases, for example with a CoRoutine that waits a certain amount of time between decreasing the amount by 1.
IEnumerator DecreaseMana() {
while(true) {
manaValue.value --;
yield return new WaitForSeconds(1f);
}
}
Ok, so I did decide to just change the mana values to floats. This was my misunderstanding because now that I know a little more about it, I definitely do not want them as strictly ints. So thank you both for helping me understand better!