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(1)
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);
}
}