while loop crashing unity

I’m writing a script that will change a Vector3 to a new value through a customizable speed, which is currently crashing unity.

while (current!= target)
       {
            distance = target- current;
            if ((current + ((distance / distance.magnitude) * changeSpeed)).magnitude < target.magnitude)
            {
                current = current + ((distance / distance.magnitude) * changeSpeed);
            } else 
            {
                current= target;
            }

        }

It doesn’t seem to be an infinite loop, yet it is still crashing unity. Any answers?

No problem, except when changeSpeed ​​is 0 …

@Pigeon, Comparing floats is always a problem. It is extremely rare, for example in your calculations, that current will ever exactly equal target, and therefore current != target is always true. So your loop never ends.

You should make it standard practice when comparing floats to get the absolute value of the difference between them and compare the result with some threshold. How close to each other do they need to be for you to judge them equal enough?

for example:

        while absolute value of float1 - float2  > 0.001f do you thing!

You have to figure out which threshold value best fits your situation.

You can compare vectors using the same concept (and you should), just by getting the magnitude of the difference between them and comparing that with a threshold.

My Mistake! I had kept changeSpeed at 0 :).

BUT I can still offer wisdom. One of the first fixes I tried when this issue came up was adding the If statement you see in the code. What this is doing is anticipating whether the new value will overpass the target, and if so, just setting the current to the target, as the distance between the two is less than the value the current one increases by every frame. SO, if your while loop is crashing, try adding an if statement with a similar function but related to your project, and that might help :slight_smile: