Can't find the error in FindClosestEnemy method

I do not udnerstand why this method dosnt work, sorry if this is a dumb question but I’m new to all this.

GameObject FindClosestEnemy() {
    		GameObject[] possibleNewTargets;
    		possibleNewTargets = GameObject.FindGameObjectsWithTag("enemy");
    		GameObject closest;
    		float distance = lightningJumpRange;
    		Vector3 position = transform.position;
    		foreach (GameObject go in possibleNewTargets) {
    			Vector3 diff = go.transform.position - position;
    			float curDistance = diff.sqrMagnitude;
    			if (curDistance < distance) {
    				closest = go;
    				distance = curDistance;
    
    			}
    		}
    		return closest;
    	}

Error; A local variable cannot be used before it is declared: closest.

Thank you.

The compiler looks at your code and sees that “closest” is only assigned a value within a loop. That loop could conceivably never run if possibleTargets is an empty list. If that happened when you tried to return it there would be no value to return.

The solution is to initialize closest with a value when created. usually this is null, like this

GameObject closest = null;