private GameObject FindTarget() { GameObject foundObject = null; Collider[] hitColliders = Physics.OverlapSphere(transform.position, m_DetectionRange); int i = 0; float distanceToClosestTrap = float.MaxValue; while (i < hitColliders.Length) { ITrap foundTrap = hitColliders[i].GetComponent(typeof(ITrap)) as ITrap; if (foundTrap != null) { if (foundTrap.GetTrapState() != TrapState.IDLE) { i++; continue; } float distanceToTrap = (foundTrap.GetWorldPosition() - transform.position).sqrMagnitude; if (distanceToTrap < distanceToClosestTrap) { distanceToClosestTrap = distanceToTrap; foundObject = hitColliders[i].gameObject; } } i++; } return(foundObject); }