I am creating a tower defence game and i am creating a turret script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Turret : MonoBehaviour
{
public LineRenderer laser;
public Transform Head;
public float Enemydistance;
public float range = 15;
public float rotationSpeed = 10f;
public float nearestEnemyDistance;
public GameObject nearestEnemy = null;
public bool targetinRange = false;
GameObject target = null;
// Start is called before the first frame update
void Start()
{
InvokeRepeating("findEnemy", 0f, 0.5f);
}
// Update is called once per frame
void Update()
{
if (nearestEnemyDistance <= range)
{
targetinRange = true;
}
if (target = null)
{
return;
}
else if (target != null && targetinRange)
{
Vector3 dir = target.transform.position - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(Head.rotation, lookRotation, Time.deltaTime * rotationSpeed).eulerAngles;
Head.rotation = Quaternion.Euler(0f, rotation.y, 0f);
}
}
public void findEnemy()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
foreach (GameObject Enemy in enemies)
{
nearestEnemyDistance = Mathf.Min(Enemydistance);
Enemydistance = Vector3.Distance(Enemy.transform.position, this.transform.position);
if (Enemydistance <= nearestEnemyDistance)
{
nearestEnemyDistance = Enemydistance;
nearestEnemy = Enemy;
}
if (nearestEnemy != null)
{
target = nearestEnemy;
}
else
{
return;
}
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, range);
}
}
I set the target = nearest enemy but target was null when i hit play.(nearest enemy is not null)
as shown here: