- Home /
2D turret system (detection problem)
Hi, I'm having some problems with detecting a transform inside a range.
When i use this script the turret will detect the enemy. But if there are multiple enemies the turret goes crazy because it changes [0] transform gameObject.....
Is there a way to detect an enemy and wait before switching the [0] or transform if the enemy leaves the area or gets killed?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyQueue : MonoBehaviour
{
public LayerMask whoisenemy;
public Vector3 turrentPos;
public float range;
public Collider2D[] enemyQueue;
public Transform enemyTransform;
void Update()
{
enemyQueue = Physics2D.OverlapCircleAll(turrentPos, range, whoisenemy);
for (int i = 0; i < enemyQueue.Length; i++)
{
enemyTransform = enemyQueue[0].transform;
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(turrentPos, range);
}
}
Answer by JxWolfe · May 16, 2020 at 09:22 PM
An easy way of doing this is changing Enemyqueue to a List - then adding enemies to that list. (if enemy == null then remove the enemy) then use [0] for the target
Thank you, I used System.Linq And I think it I don't see any switching with my transform now. But When the enemy goes out of range the Turret still detects it. How do I set the enemy to Null when it's out of range? Here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class EnemyQueue : $$anonymous$$onoBehaviour
{
public Layer$$anonymous$$ask whoisenemy;
public Vector3 turrentPos;
public float range;
public List <Collider2D> enemyQueue;
public Transform enemyTransform;
void Update()
{
enemyQueue = Physics2D.OverlapCircleAll(turrentPos, range, whoisenemy).ToList();
foreach (Collider2D col in enemyQueue)
{
Debug.Log("FOUND: " + col.gameObject.name);
Debug.Log(enemyQueue.Count + col.gameObject.name);
if (enemyQueue.Count == 1) { //see who is first
enemyTransform = col.gameObject.transform;
}
if(col.gameObject.transform != enemyTransform)
{
Debug.Log("changed transform");
enemyQueue.Remove(col);
}
if (col.gameObject.name == "GameObject") {
enemyQueue.Remove(col); // this is an extra collider I added to the enemy. I only want the Enemy collider in the list
}
}
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(turrentPos, range);
}
}