Mathf.Infinity

Can someone explain how Mathf.infinity is working in this script? The script is supposed to turn an instantiated bullet towards the closest target, but I can’t really tell what Math.infinity is actually doing.

   // Update is called once per frame
	void Update () 
	{

		float nearestDistance = Mathf.Infinity;
		GameObject nearestEnemy = null;
		foreach(GameObject obj in GameObject.FindGameObjectsWithTag("Enemy"))
		{
			//float distance = Vector3.Distance(transform.position - obj.transform.position);
			float distance = (transform.position - obj.transform.position).sqrMagnitude;
			if(distance < nearestDistance)
			{
				nearestDistance = distance;
				nearestEnemy = obj; // set 1 gameObject
			}
		}
		if(nearestEnemy != null)
		{
			transform.rotation = Quaternion.LookRotation(nearestEnemy.transform.position - transform.position);
		}
	}

It’s a script to get the nearest GameObject with the tag “Enemy”. It initially sets the nearestDistance to Mathf.Infinity so it will consider all the GameObjects in the scene.

If you have an actionRadious for example, you might want to initially set the nearestDistance to the radious so the algorithm does not consider GameObjects farther than that.

The trick is in if(distance < nearestDistance). If the GameObject is farther than the nearest distance encountered so far, it won’t take it into account.