- Home /
Use of unassigned variable? Script from script reference
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.
Answer by PAEvenson · Jul 18, 2013 at 02:36 PM
Here is your problem:
GameObject closestPlayer;
To fix change to this:
GameObject closestPlayer = null;
That way if it fails to find an enemy it can return null and not throw an exception.
thanks, I understand how it works, this way it assigns it but doesn't kinda :p
it's not working :/ could you try the script yourself and fix it?`using UnityEngine; using System.Collections;
public class EnemyScript : $$anonymous$$onoBehaviour {
public float health = 100;
public float speed = 100;
public GameObject[] gos;
public GameObject closestPlayer = null;
public float distance;
void FixedUpdate(){
transform.LookAt(closestPlayer.transform.position);
FindClosestEnemy();
}
GameObject FindClosestEnemy() {
gos = GameObject.FindGameObjectsWithTag("Player");
distance = $$anonymous$$athf.Infinity;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - transform.position;
float curDistance = diff.sqr$$anonymous$$agnitude;
if (curDistance < distance) {
closestPlayer = go;
distance = curDistance;
}
}
return closestPlayer;
}
}`
Your answer
![](https://koobas.hobune.stream/wayback/20220613110353im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Saving final score and displaying on main menu 1 Answer
null texture passed to GUI.DrawTexture 0 Answers