Checking for quaternion values to not be NaN

Every so often, a camera rotation script would output (NaN,NaN,NaN,NaN) for rotation… Is there a way to check for output that is not NaN before assigning the rotation?

I have problems with either NaN or a zero quaternion showing up from time to time, and throwing an error somewhere inside Quaternion.Lerp.

To deal with that, I like to use an extension method - I keep a static class with a few of them in each project, utilities to do things like check if a UnityEngine.Object is null off of the main thread. Here’s just the relevant part:

public static class UnityExtensionMethods {
	/// <summary>
	/// Determines whether the quaternion is safe for interpolation or use with transform.rotation.
	/// </summary>
	/// <returns><c>false</c> if using the quaternion in Quaternion.Lerp() will result in an error (eg. NaN values or zero-length quaternion).</returns>
	/// <param name="quaternion">Quaternion.</param>
	public static bool IsValid(this Quaternion quaternion)
	{
		bool isNaN = float.IsNaN(quaternion.x + quaternion.y + quaternion.z + quaternion.w);

		bool isZero = quaternion.x == 0 && quaternion.y == 0 && quaternion.z == 0 && quaternion.w == 0;

		return !(isNaN || isZero);
	}
}

This lets me write

if(myQuaternion.IsValid())

before using a quaternion in any Lerps or assigning it as a rotation.

if(!System.Single.IsNaN( someVariable ))
// assign rotation

Well, i know this is a old post but, i will help others with simple soluction for check if “float variable” is a NaN or not.

if(float.IsNaN("YOURFLOATVARIABLE")){
      //Your condition...
}
else{
      //Your "else" condition
}

This worked on my browsers JS console:

if (!NaN) console.debug("HI");

Hope this helps.