Moving object with Coroutine and while loop, problem

I am trying to rotate a 3D gameobject towards a 3D Cylinder using this function:

   IEnumerator RotateTowardsCylinder()
   {
       bool waiting2Seconds = false;

       Vector3 targetRotate = new Vector3(cylinder.position.x - transform.position.x, cylinder.position.y - transform.position.y, cylinder.position.z- transform.position.z);
       Vector3 newDirection = Vector3.RotateTowards(transform.forward, targetRotate, 0.01f, 0);
       transform.rotation = Quaternion.LookRotation(newDirection, transform.up);


       while (targetRotate.normalized.x != newDirection.normalized.x || targetRotate.normalized.z != newDirection.normalized.z)
       {
           transform.rotation = Quaternion.LookRotation(newDirection, transform.up);
            targetRotate = new Vector3(cylinder.position.x - transform.position.x, cylinder.position.y - transform.position.y, cylinder.position.z - transform.position.z);
            newDirection = Vector3.RotateTowards(transform.forward, targetRotate, 0.01f, 0);

           Debug.Log("targetRotate " + targetRotate.normalized + "newDirection  " + newDirection.normalized);

           yield return null;
       }
       waiting2Seconds = true;
       Debug.Log("waiting 2 sec " + waiting2Seconds);
       yield return new WaitForSeconds(2.0f);

       StartCoroutine(MoveTowardsCylinder());
       moveFunctionRuns = true;
       Debug.Log("MoveTowardsCylinder " + moveFunctionRuns);
   }

It doesn’t seem to ever go out of the while loop, because I dont see my Debug.Log messages appearing in the console. Why is this? Please help, I would be grateful!

  1. Debug.Log(Vector3) only prints out one decimal place, so you can’t rely on that.

  2. You shouldn’t use “==” or “!=” to compare floats. You should use Mathf.Approximately(f1, f2) to compare floats.

  3. But, in your case the value differences don’t seem to be small enough to use Mathf.Approximately.

You can try seeing if the difference is smaller than some custom threshold, like 0.01:

while (Mathf.Abs (targetRotate.normalized.x - newDirection.normalized.x) > 0.01f || Mathf.Abs (targetRotate.normalized.z - newDirection.normalized.z) > 0.01f) {

Never ever compare two float values for (in)equality. They may not ever be precisely equal down to the very last bit.

Even with Mathf.Approximately this may not work.