this seems like a really stupid question to have to be asking but Unity can't seem to manage to do a simple maths sum. (Its probably me and I'll kick myself for it afterwards I'm sure)
a code sample:
this simple piece of code in a much larger script is giving me a lot of hassle. For some reason Unity decides that the answer to 3/4 is 0?!
whereas in this example:
it works out the right answer. I need to use the equivalant to the first example as I am using variables instead of the simple numbers
Any help would be much appreciated. I'm guessing its just me having a dumb moment
You may need to define the type as shown above. In your second example, you use a floating point value so Unity automatically defines it as a float. I believe that may be your problem.
answered Mar 30 '11 at 07:49 PM
The reason that your not getting the correct answer is because an "int" is defined as an integer (If you don't know what an integer is, its a whole number).
Edited at the request of Statement: (Whole numbers are numbers with no decimal part value. Ex: 2, 30012, 4239842. These are not whole numbers: 1.2, 1.4, 54.4 )
When you divide with integers, it rounds to the nearest whole number. In this case, its closer to 0, so it rounds down. Like numerous people have already said, adding ".0" would have converted it to a floating point decimal (float) which would have an integer plus the string of digits past the decimal.
Another way to get around this is to cast. For instance, you might be using values that are awkward if they aren't integers (health or experience are common variables that are best left as ints).
And this is how you cast in C# for you C# lurkers :P
answered Mar 31 '11 at 01:40 AM