I’m making a tower-defense game. My defense targeting with Overlapshere. First target is working true.
After the first target left the area, my weapon Targeting the 2nd object from the new targets in the area once, after turning to 1st object in the are again.
After that, the target does not change until the object leaves the area. However, when the object leaves the area, it is targeted at the second object once again, then returns to the first target again in the area.
I hope I explained it confusingly.
Weapon Controller Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class WeaponController : MonoBehaviour
{
[SerializeField] private float fireRate;
[SerializeField] private float attackRadius;
[SerializeField] private Bullet bulletPrefab;
private Collider[] enemies;
private EnemyController currentEnemy = null;
private void Start()
{
InvokeRepeating(nameof(ScanArea), 0.1f, fireRate);
}
private void OnDrawGizmos()
{
Gizmos.color = Color.cyan;
Gizmos.DrawWireSphere(transform.position, attackRadius);
}
private void ScanArea()
{
enemies = Physics.OverlapSphere(transform.position, attackRadius);
foreach (Collider enemy in enemies)
{
if (enemy.gameObject.TryGetComponent(out EnemyController enemyScript))
{
float distance = Vector3.Distance(transform.position, enemy.transform.position);
if (distance < attackRadius)
{
currentEnemy = enemyScript;
}
}
}
if (currentEnemy)
{
Bullet bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
bullet.SetTarget(currentEnemy.transform);
}
}
private void Update()
{
if (currentEnemy)
{
Vector3 direction = currentEnemy.transform.position - transform.position;
direction.y = 0;
transform.rotation = Quaternion.LookRotation(direction);
}
}
}
if the method I want is complicated or has poor performance:
Alternative: After the first target leaves the area, the defense can target the nearest enemy. However, the selected target must not change (except for death or leaving the area).