I’m trying to make a script that will target the closest object with a tag.
I am using a script off of http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html.
But i get the error code…
Assets/findClose.cs(27,24): error CS0165: Use of unassigned local variable `closest’
Here is the code I am working on.
using UnityEngine;
using System.Collections;
public class findClose : MonoBehaviour {
public float damage = 100; //amount of damage to inflict
public float distance; //distance to target
public float maxDistance = 5.0f; //when target is in damage range
public GameObject Target; //current target
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");
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 Update () {
//find target with tag
Target = FindClosestEnemy ();
//find distance to target
distance = Vector3.Distance(transform.position, Target.transform.position);
//if within damaging range
if(distance < maxDistance ){
//send message to targets script
Target.SendMessage("ApplyDamage", damage);
}
}
}