- Home /
The question is answered, right answer was accepted
operator == is not working every time to find if a list contains item in another list
Hi i am trying to see if one list contains any item from another list by this code
for (int j = 0; j < spawnedCoins.Count; j++) {
for (int i = 0; i < connectedTiles.Count; i++) {
if (spawnedCoins[j].transform.position.x == connectedTiles[i].x && spawnedCoins[j].transform.position.y == connectedTiles[i].y)
{
coinsCollected++;
Destroy (spawnedCoins [j]);
spawnedCoins.RemoveAt (j);
}
}
}
However Sometimes it finds a match and destroys the object but then sometimes it does not find a match where it is clearly a match. I have confirmed many times that the x and y values of both elements are the same but still NO match is found and it does not go inside if statement. And thus coinsCollected score is not added and coins are not deleted in game.
I have also used contains like this but with same problems
for (int j = 0; j < spawnedCoins.Count; j++) {
if (connectedTiles.Contains (spawnedCoins[j].transform.position)) {
coinsCollected++;
Destroy (spawnedCoins [j]);
spawnedCoins.RemoveAt (j);
}
}
Can anyone tell me why this is happening? Thanks
Answer by Paul-Jan · Mar 31, 2016 at 05:36 PM
Are x and y floats with fractional values (i.e. non-integers)? In that case, two values that show up as "the same" in the debugger (logs, printf, whatever) might not have, in fact, the exact same underlying value as there is a round off in the number of decimals that is displayed.
Try using Mathf.Approximately to compare the values, or use your own equality definition with an appropriate epsilon.
Or, even beter, directly use Vector3/Vector2 == operator on position. The default Vector2 equality operation in Unity already does a "really close to being equal" check.
x and y are floats but not their values are always integers. your last advise to use == on vector 2 seems to have worked. I dont know y i just didnt do that in the first place. THanks