Hi, I’ve recently decided to start coding in c#, so today I was going to do some AI, but I started having this error: Assets/Scripts/EnemyScript.cs(23,16): error CS0165: Use of unassigned local variable `closestPlayer’ it’s weird because the script is almost the same from the script reference page, this is how my script is at the moment:
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour {
public float health = 100;
public float speed = 100;
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player");
GameObject closestPlayer;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closestPlayer = go;
distance = curDistance;
}
}
return closestPlayer;
}
}
I can’t find any mistake in my script so I don’t understand what is wrong, by the way I also tried to call FindClosestEnemy() in the FixedUpdate void, the error was the same. Any help would be appreciated, thanks in advance.