float to int? error

    public int MaxHealth = 10f;
    int currentHealth;

i have this line of code and public int attackDamage = 10f; are getting striked for error CS0266* how can i fix this

*cannot implicitly convert type ‘float’ to ‘int’. An explicit conversion exists (are you missing a cast?)

it is what it says it is

you can’t implicitly convert a float to an int.

In this, since it’s an assignment, you’ve done “10f”, the “f” means “float”. Remove the “f” and it’s an int.

public int attackDamage = 10;

If you had a float variable and tried to assign that to an int like so:

float a = 10f;
int b = a;

You’d also get the same error… to fix this you “cast” it:

float a = 10f;
int b = (int)a;

Note that when casting from float to int you’d lose any fractional information. Furthermore floats can be out of the range of ints since float.MaxValue is significantly larger than int.MaxValue. It doesn’t error out, you just will get weird values back.

thanks i thought with c# you had to put f after every number. thanks for letting me know because i am new to the whole game development and coding scene

Nope, the ‘f’ denotes that it is a “float”. There are several suffixes for common numeric types. As well as implicits.

implicits:
int - any number with no fraction part in format ####
double - any number with fraction part in format ####.####

explicits:
double - suffix ‘d’
float - suffix ‘f’
long - suffix ‘L’
ulong - suffix ‘UL’
decimal - suffix ‘m’ (for money)
int, but written in binary - prefix ‘0b’
int, but written in hex - prefix ‘0x’

All other numeric types (short, byte, etc) can be written as ‘int’ but cast to its type like so:

short i = (short)5;

Though honestly, you don’t even need to put the cast as the compiler has no problem just doing:

short i = 5;

You can read through these articles which cover the common numeric types:
integers:

floating-point: