- Home /
Help adjusting my code
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;
}
}
Answer by tanoshimi · Aug 13, 2017 at 06:31 AM
Don't call InvokeRepeating in Update - you'll end up queuing an infinite number of method calls and crash your game very quickly. If tou only want to retarget every half second:
void Start(){
InvokeRepeating("FindNearestEnemy", 0f, 0.5f);
}
Even in Start it doesn't track and do what it is supposed to do
I get NullReferenceException: Object reference not set to an instance of an object Turret.FindNearestEnemy () (at Assets/Scripts/Turret.cs:28)
Give us a clue.... what line does that refer to?
float dist = Vector3.Distance(player.transform.position, enemyItem.transform.position);
Answer by Komayo · Aug 13, 2017 at 07:33 AM
Also after find the nearest target, dont forget to setup the facing of the player/turret to him.
I had about 6 yesterday but then when I tried to give you some I only had 1, but whatever