Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

If statement gets passed over even though the conditions shouldn't let it

Discussion in 'Scripting' started by All_American, Apr 17, 2022.

  1. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    I have this if statement:

    Code (CSharp):
    1.  
    2.              Debug.Log(Mid_Offset_Floor_Length_X + " " + Floorlength + " " + Mid_Offset_Floor_Width_Y + " " + Floorwidth);
    3.              if (Mid_Offset_Floor_Length_X == Floorlength && Mid_Offset_Floor_Width_Y < Floorwidth)
    4.             {
    5.                 Debug.Log("X is equal to length, Y is less than width.");
    6.                 Debug.Log(Mid_Offset_Floor_Length_X);
    7.                 Debug.Log(Floorlength);
    8.  
    9.                 NumofFloors -= 1;
    10.                 floorNum += 1;
    11.                 offsetFlrNum = 1;
    12.             }
    I have debugged TF out of it and I know what the values are and that's what they are. I have others that are similar, but this one just does not want to work.

    I need another set of eyes on this.

    Here's the debug log before the statement

    Code (CSharp):
    1. 61.214 61.214 24.638 36.83
     
  2. nilsdr

    nilsdr

    Joined:
    Oct 24, 2017
    Posts:
    374
    https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html use this instead of the equality operator
     
    All_American likes this.
  3. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,739
    so you are directly comparing floats to each other for equality. i would rewrite it in a such a way you can avoid this, since you will have issues with floating point precision which is likely the cause of your issue.

    if you cant change the logic you might want to use https://docs.unity3d.com/ScriptReference/Mathf.Approximately.html
    instead of a equality check between floats
     
    All_American likes this.
  4. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    I rounded them to two decimals. Thought that would avoid that.

    Also I have another statement doing the exact same thing that's working as expected....I'll try it.
     
  5. All_American

    All_American

    Joined:
    Oct 14, 2011
    Posts:
    1,528
    passerbycmc likes this.