Hi there, I’m trying to build a turret in a tower defence that kills the enemies but doesn’t shoot, so it’s a range tower. When I find the enemy then I want to destroy() but it doesn’t let me do it.
using UnityEngine;
using UnityEngine;
public class Firewall : MonoBehaviour
{
[Header("Attributes")]
public float range = 0.6f;
[Header("Unity Setup")]
public string enemyTag = "Enemy";
public Transform target;
void Start(){
InvokeRepeating("UpdateTarget", 0f, 0.5f);
}
private void UpdateTarget()
{
GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
float shortestDistance = Mathf.Infinity;
GameObject nearestEnemy = null;
foreach(GameObject enemy in enemies)
{
float distanceToEnemy = Vector2.Distance(transform.position, enemy.transform.position);
if(distanceToEnemy < shortestDistance)
{
shortestDistance = distanceToEnemy;
nearestEnemy = enemy;
}
}
if(nearestEnemy != null && shortestDistance <= range)
{
target = nearestEnemy.transform;
} else
{
target = null;
}
}
public void Impact()
{
Debug.Log("Impact with virus");
Destroy(target.gameObject);
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, range);
}
}