using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TargetFinder : MonoBehaviour {

    public string targetTag;

    private GameObject closest;

    void Start() {
        if (targetTag == null)
            targetTag = "";
    }

    public GameObject GetClosest() {
        GameObject closest = null;
        float closestDistance = float.PositiveInfinity;
        float distance;

        GameObject[] objects = GameObject.FindGameObjectsWithTag(targetTag);

        foreach (GameObject obj in objects) {
            distance = Vector3.Distance(transform.position, obj.transform.position);

            if (closest == null) {
                closest = obj;
                closestDistance = Vector3.Distance(transform.position, obj.transform.position);
            }
            else {
                if (distance < closestDistance)
                    closest = obj;
            }
        }

        return closest;
    }
}
