- Home /
Scipting Api script not working
So i wanted to find the closest gamobject wih the tag "WallTarget1", so i went online and searched how to do that and most of them pointed to the second script of "GameObject.FindGameObjectsWithTag" scripting api Page(link) so i copied it in a test script(C#), and changed the name, the tag and the Called it in the Void Start instead of Void Example and now if i try to print the name i get the eror Assets/Test.cs(19,24): error CS0165: Use of unassigned local variable `closest' Can anyone help me?
here is how my scrpt looks
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("WallTarget1");
GameObject closest;
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) {
closest = go;
distance = curDistance;
}
}
return closest;
}
void Start() {
print(FindClosestEnemy().name);
}
}
Answer by Kiwasi · Apr 20, 2015 at 02:04 AM
Just a hunch, but try changing line 8 to:
GameObject closest = null;
It will still cause a null reference error if there are no GameObjects in gos
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity C# api tutorial? 1 Answer
Kongregate API not connecting C# 2 Answers