How do I find the closest target with a tag? c#

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

It feels like you’re returning “closest” before properly assigning into it. Check your code for this part:

GameObject closest; // at this time, object is null
    if (curDistance < distance)
     closest = go;
    else
    ?
return closest; // null when hits else

You should handle null case outside if you want function this way.

here is part of an old JS script I used to use.

public var gos : GameObject[];

// Print the name of the closest enemy
print(FindClosestResource().name); 
	
// Find the name of the closest enemy
function FindClosestResource () : GameObject
{
// Find all game objects with tag Enemy
gos = GameObject.FindGameObjectsWithTag("Resource");
 
var closest : GameObject; 
var distance = Mathf.Infinity; 
var position = transform.position; 

// Iterate through them and find the closest one
for (var go : GameObject in gos)
{ 
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude; 
if (curDistance < distance)
{ 
	closest = go; 
	distance = curDistance; 
}
 
} 
return closest;	
}

I know its not exactly what you were looking for, but maybe It will help you figure out an answer

:slight_smile: