Look at closest Tag C#

Hi, I’ve been trying to learn and understand looking at closest tag in C#.
Would like some pointers to point me in the right direction :smiley:
using UnityEngine;
using System.Collections;
public class NetworkEnemeyFighter : MonoBehaviour {

	Vector3 position;
	Quaternion rotation;
	public float speed = 20f;  //speed
	public float LookAtSpeed = 20f; // the speed of the ship turns.
	public float smoothing = 10f;
	public float HealthAIFighter = 50f;  //Health to send over network
	public GameObject Users; // used to search for gmae object with tagg Users
	public float Distance; //using this to diterman distance of closest user some how....
	// AI SCRIPT TO CONTROLL BEHAVIOUR OF ENEMEY FIGHTERS.

	void Start (){
		StartCoroutine("EnemyFighterData");
	}



	void Update ()
	{
		Users = GameObject.FindWithTag ("Users");
	transform.LookAt(Users);
// look at Closest user.  computed offline, potion rotation sent online so calculations donot laggg PVP/.
	}




	
	void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
	{
		if(stream.isWriting)
		{
			stream.SendNext(transform.position);
			stream.SendNext(transform.rotation);
			stream.SendNext(HealthAIFighter);

		}
		else
		{
			position = (Vector3)stream.ReceiveNext();
			rotation = (Quaternion)stream.ReceiveNext();
			HealthAIFighter = (float)stream.ReceiveNext();

		}
	} // end of Stream







	IEnumerator EnemyFighterData()   //send potision / rotaion of AI fighter to all users.
	{
		while(true)
		{
			transform.position = Vector3.Lerp(transform.position, position, Time.deltaTime * smoothing);
			transform.rotation = Quaternion.Lerp(transform.rotation, rotation, Time.deltaTime * smoothing);
			yield return null;
		}
	}



	}

For me the easiest way to do this is to get all gameobject with your tag and compare their deistances.

            GameObject[] goArray = GameObject.FindGameObjectsWithTag("MyBestTag");

		if (goArray.Length == 0)
			return;

		GameObject closest = goArray[0];
		foreach (GameObject go in goArray) {
			if (Vector3.Distance(transform.position, go.transform.position) < Vector3.Distance(transform.position, closest.transform.position))
				closest = go;
		}

I hope this help…

Something like this might work for you. I’ve not tested this code so you probably need to tweak it to get it to work but idea should be clear.

float shortest = float.PositiveInfinity;
Transform closest = null;

var users = GameObject.FindGameObjectsWithTag("Users");
foreach (var user in users) {
    float distance = Vector3.Distance(transform.position, user.transform.position);
    if (distance < shortest) {
       shortest = distance;
       closest = user.transform;
    }
}

Now you know what is the closest target and then just turn towards it.