I have the following code in order to make my turret face the nearest target and I cant get it to work. Any suggestions?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class Turret : MonoBehaviour
{
GameObject enemies;
GameObject player;
GameObject closestEnemy;
private Vector3 target;
int count = 0;
private void Update()
{
InvokeRepeating("FindNearestEnemy", 0f, 0.5f);
target = closestEnemy.transform.position;
}
GameObject FindNearestEnemy()
{
float minDistance = Mathf.Infinity;
enemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach (GameObject enemyItem in enemies)
{
float dist = Vector3.Distance(player.transform.position, enemyItem.transform.position);
if (count == 0)
{
minDistance = dist;
closestEnemy = enemyItem;
count++;
}
else
{
if (dist < minDistance)
{
minDistance = dist;
closestEnemy = enemyItem;
}
}
}
return closestEnemy;
}
}