Error: Input position is { NaN, NaN, NaN }.

Hello all,

I am getting this error only on rare occasions (so harder to figure out where).
It shows up inside an Update loop, on this line:

transform.position = Utils.MoveTowardsPlayer( transform.position, activeMagnetZone, activeMagnetSpeed );

The MoveTowardsPlayer function is here:

	public static Vector3 MoveTowardsPlayer( Vector3 from, float magnetZone, float magnetSmooth ) {
		if( magnetZone == 0 || magnetSmooth == 0 ) return from;

		Vector3 to = Dispatch.PlayerPos;
		float distance = Vector3.Distance( from, to );
		
		if( distance == 0 || distance > magnetZone ) return from;
		// Above line originally was
		// if( distance > magnetZone ) return from;

		float smooth = magnetSmooth;
		smooth *= (magnetZone-distance)/distance;
		return Vector3.Lerp( from, to, Time.deltaTime * smooth );

        // Alt method
        // return Vector3.SmoothDamp( transform.position, magnetPos, ref magnetVelocity, magnetSmoothTime );
	}

So, the only place I suspected could cause the error, was if distance is 0, so I am now checking for it as well - but I am not sure this is the reason, as I would have expected a “division by zero” error.

Can anyone help in figuring out which is the cause for the error?

I’m not sure as to why you’re getting non number values, but since your problem only occurs occasionally you won’t have any problem skipping calculation for 1/30th of a second if you have bad values.

Since there is no way to actually declare a ‘NaN’ value, you have to check using float.isNaN();

if (!float.IsNaN(transform.position.x) && !float.IsNaN(transform.position.y) && !float.IsNaN(transform.position.z))
{
     //Do stuff
}

Im a bit late but i replicated this nan issue. it occurred from adding a mesh collider to a model that already had a character controller and they collided with eachother so for anyone with this issue remove the mesh collider

Here, just put this right before your “return Lerp”:

Debug.Log(
    "MoveTowardsPlayer: 

“+
" from = " + from + "
" +
" magnetZone = " + magnetZone + "
" +
" magnetSmooth = " + magnetSmooth + "
" +
" to = " + to +”
" +
" distance = " + distance + "
" +
" smooth = " + smooth + "
"
);

The problem with NaN values is that they spread like cancer. Any calculation with a NaN value will result in NaN as well. Maybe the NaN comes from an external calculation which is not in your function but is transferred into it.