Protect Against NaN

The first way I did it was very simple. I wrapped the actual transformation change in an if statement, like so:

if (period != 0) 
      transform.position = startingPosition + offset;

Another way you could do it is using the Range item, just like we did with the movementFactor. To prevent NaN, the minimum range would be a very small number such as 0.01, with a maximum of let’s say 10, because anything above that is hardly moving. This time, it would be done at the beginning of the code.

[SerializeField] float period = 2f;


[Range(0.01f, 10f)] [SerializeField] float period = 2f;

As you can see in the screenshot below, I now get a value of 0.01 when I drag the period slider all the way to the left. This method is much better than my first one, because unlike using the if statement, it completely removes any possibility of setting the period to 0.


Privacy & Terms