using System; using UnityEngine; public class DetectEntities : MonoBehaviour { [SerializeField] private Entity thisEntity; private void OnTriggerEnter2D(Collider2D other) { if (!other.CompareTag(thisEntity.tag) && other.TryGetComponent(out Entity isEntity)) { thisEntity.entitiesInRange.Add(isEntity); thisEntity.closestEntity = FindClosestEntity(); } } private void OnTriggerExit2D(Collider2D other) { if (other.TryGetComponent(out Entity isEntity) && thisEntity.entitiesInRange.Contains(isEntity)) { thisEntity.entitiesInRange.Remove(isEntity); if (thisEntity.closestEntity == isEntity) { thisEntity.closestEntity = FindClosestEntity(); } } } private Entity FindClosestEntity() { Entity currentClosestEntity = null; foreach (Entity entityFound in thisEntity.entitiesInRange) { if (!currentClosestEntity || Vector3.Distance(entityFound.transform.position, thisEntity.transform.position) < Vector3.Distance(currentClosestEntity.transform.position, thisEntity.transform.position)) { currentClosestEntity = entityFound; } } return currentClosestEntity; } }