# [#C] Why is my IF-statement trigger

I have two Lists:

• “Singleton.Instance.master_GameObject_List” with GameObject’s

• “originalData_List” a string list with: 1) GameObject tag, 2) position.x as string, 3) position.y as string

I use the following code:

``````int y = 0;

foreach (GameObject aGO in Singleton.Instance.master_GameObject_List) {

float XX = float.Parse (originalData_List [y + 1]);

float YY = float.Parse (originalData_List [y + 2]);

if (aGO.tag == "H9_1B") {
print ("aGO: " + aGO.tag + " & " + aGO.transform.position.x + " & " + aGO.transform.position.y + " ||| " + originalData_List[y] + " & " + XX + " & " + YY);

if (aGO.transform.position.x != XX) {
print ("HIT: " + aGO.tag + " | " + aGO.transform.position.x + " | " + XX);
}
}

y = y + 3;

}
``````

Using this at line 15: “if (aGO.transform.position.x != XX) {” i get the following print:

``````aGO: H9_1B & -0.03255639 & -0.03505984 ||| H9_1B & -0.03255639 & -0.03505984

HIT: H9_1B | -0.03255639 | -0.03255639
``````

When changing line 15 to: “if (aGO.transform.position.x == XX) {” i get the following result:

``````aGO: aGO: H9_1B & -0.04436753 & 0.01810524 ||| H9_1B & -0.04436753 & 0.01810524
``````

I probably do not see the “simple” solution to this but from my aspect the x’s is the same. The difference between the positions is just how the code layout the GameObjects, a bit random, so it does not matter.

I guess it can be the something with the Parse statement, but i just do not get it.

By and large, comparing floats using == and != is asking for trouble. Floats are notoriously imprecise on the very small scale, and even writing a number to a string and reading it back in can cause the number to be slightly different. It wouldn’t surprise me if those two floats - even though they are being output to the same string of digits - are different on the very small scale. (This is expected behavior for floats.)

1. If you must do this comparison with floats, try checking to see if they’re within a particular range, or use Mathf.Approximately to compare them.

2. On the other hand, 9 times out of 10, if you’re using == on a float, you’re probably using the wrong data type, conceptually. In this case, it seems to me (with what little glimpse into the code I have here) that you’re doing something with grid cells, and therefore you might be better off storing and comparing ints than floats.

Thanks, will try!

@StarMantra that worked perfectly, a BIG thank you for that learning

I changed line 15 to: “if (!Mathf.Approximately(aGO.transform.position.x, XX)) {”