Can't use declared variable to find nearest Object

Hello everybody,

I want to “respawn” a player to the race track when he falls off the map and touches a trigger volume, this is my code :

GameObject GetClosestObject(string tag) 
	{
		GameObject ClosestObject;
		GameObject[] gos = GameObject.FindGameObjectsWithTag(tag);

		float distance = Mathf.Infinity;

		foreach (GameObject go in gos) 
		{
			Vector3 diff = go.transform.position - transform.position;
			float curDistance = diff.sqrMagnitude;

			if (curDistance < distance) 
			{
				ClosestObject = go;
				distance = curDistance;
			}
		}

		return ClosestObject;
	}

But I get this error in the last line :

error CS0165: Use of unassigned local variable `ClosestObject’

Anyone knows what I’m doing wrong?

On line 3, just do:

GameObject ClosestObject = null;

The compiler is complaining that if there is no objects in ‘gos’, then you will be returning an uninitialized ‘ClosestObject’.