-1

So, I was trying to do some stuff in unity and i wrote something like this

private IEnumerator RotateToNormal()
    {
        while (hingePoint.eulerAngles.z > 20)
        {
            float d = Time.deltaTime * 500;
            hingePoint.eulerAngles = new Vector3(hingePoint.eulerAngles.x, 0, Mathf.Clamp(hingePoint.eulerAngles.z - d, 20, 90));
            transform.position = hingePoint.position + hingePoint.rotation * new Vector3(camDist, lift, 0);
            transform.LookAt(hingePoint);
            Debug.Log(hingePoint.eulerAngles.z);
            yield return null;
        }
        inSelection = false;
    }

As you can see, it should bail out from while() loop as variable equal to 20 and it reaches 20(Debug.Log and debugger shows that in hingePoint.eulerAngles.z = 20)
However, when it becomes equal to 20 it does not quit while() loop I was trying to change operators(to !=), types, I tried some if statements in loop, and apparently it didn't work. Interesting that almost same code block works just fine

private IEnumerator RotateToTop()
    {
        inSelection = true;
        while (hingePoint.eulerAngles.z < 90)
        {
            float d = Time.deltaTime * 500;
            hingePoint.eulerAngles = new Vector3(hingePoint.eulerAngles.x, 0, Mathf.Clamp(hingePoint.eulerAngles.z + d, 0, 90));
            transform.position = hingePoint.position + hingePoint.rotation * new Vector3(camDist, lift, 0);
            transform.LookAt(hingePoint);
            yield return null;
        }
    }

So, as I figured for some reason program thinks that variable is not equal to 20 when it is equal to 20, and there's the question: How can that be?

DLWHI
  • 71
  • 5
  • but you cannot be sure, that hingePoint.eulerAngles.z is 20.0f it could be 20.0000000000001f – Starbax Sep 23 '20 at 21:49
  • 1
    Relevant: [Compare floats in Unity](https://stackoverflow.com/questions/39898301/compare-floats-in-unity) – John Wu Sep 23 '20 at 21:51

2 Answers2

1

Use Mathf.Approximately when comparing floats and you expect them to be equal or nearly equal to some other value:

private IEnumerator RotateToNormal()
{
    while (!Mathf.Approximately(hingePoint.eulerAngles.z, 20.0f))
    {
        float d = Time.deltaTime * 500;
        hingePoint.eulerAngles = new Vector3(hingePoint.eulerAngles.x, 0, 
                Mathf.Clamp(hingePoint.eulerAngles.z - d, 20, 90));
        transform.position = hingePoint.position + hingePoint.rotation 
                * new Vector3(camDist, lift, 0);
        transform.LookAt(hingePoint);
        Debug.Log(hingePoint.eulerAngles.z);
        yield return null;
    }
    inSelection = false;
}
Ruzihm
  • 19,749
  • 5
  • 36
  • 48
0

Eulerangles returns a Vector3 and Vector3.x/y/z is a float. When comparing float and e.g. int(or other floats) you shold use Math.Abs.

Starbax
  • 1,005
  • 2
  • 12
  • 32