0

I use unity and visual studio 2017 for debugging and editing my unity code and i created a bool function, but when it returns true the if statement will not do what is inside :-

My Function:-

private bool EnemyClosed(float enemyv, float playerv)
{
    for(float i = -0.9f; i<=0.9f; i+=0.1f)
        if (enemyv == (playerv + i))
            return true;
    return false;
}

The error is in there if (enemyv == (playerv + i)) return true; i debugged the code while the enemyv equals to (playerv + i) but it wont return true and i dont know why, is there any error please?

Edit :-

I know i can't compare floats using equals sign but when i compare them using Mathf.Approximately function it needs some time to find the result, i saw this while i was debugging my program and i used immediate window to find their equality using above function allways it spent some time to find the result so i don't want to use Mathf.Approximately function so please help me to find some easy code to compare them.

Azhy
  • 704
  • 3
  • 16
  • 1
    Are you sure that they're actually equal? When you're debugging at the point where it should return true, use the immediate window to run `enemyv == (playerv + i)`. – ProgrammingLlama Jun 29 '18 at 12:21
  • 6
    `==` doesn´t work well together with floating-point numbers, as those cannot be stored properly into the memory. To avoid this you should allways introduce some small buffer, e.g. by using `Math.Abs`. – MakePeaceGreatAgain Jun 29 '18 at 12:21
  • [Possibly related](https://stackoverflow.com/questions/753948/why-is-floating-point-arithmetic-in-c-sharp-imprecise) – ProgrammingLlama Jun 29 '18 at 12:21
  • https://stackoverflow.com/questions/3874627/floating-point-comparison-functions-for-c-sharp – DavidG Jun 29 '18 at 12:22
  • I always use {} after for and if statements to make them easier to read. I suspect @HimBromBeere has hit on the issue – David Christopher Reynolds Jun 29 '18 at 12:22
  • 1
    Don't check equality on float (they are always approximated), use a range if you really have to use floats, or just switch to integers and "return" to float only at end of calculation, in your case yu can do: `int pv = playerv * 10; for (int i=-9; i<9; ++i) /*then check against integers*/` – DDS Jun 29 '18 at 12:26
  • This question is not duplicate but the answer of @DDS is right because i tried at the immediate window the two floats were `-3.7` and `-3.7` and when i wrote `==` for them it sais false but when i wrote approximately the output changes to true, so thank you all guys you fixed my problem. – Azhy Jun 29 '18 at 12:37
  • Why dont you do : `public static bool EnemyClosed(float enemyv, float playerv) { for (float i = -0.9f; i <= 0.9f; i += 0.1f) playerv = playerv + i; if (enemyv == playerv) return true; return false; ` – Creed Jun 29 '18 at 13:06

0 Answers0