I am trying to get the closest target to the unit using Physics2D.OverlapCircleAll, but I do not think that the coroutine is actually running and I don’t know how to fix it. Please help.
using UnityEngine;
using System.Collections;
public class Target : MonoBehaviour
{
public LayerMask layer;
public float targetRange = 2f;
public Transform target;
public float currentDist;
public Transform currentTarget;
public Collider2D[] cols;
private RaycastHit2D hit;
private Vector2 thisPos;
// Use this for initialization
void Start ()
{
StartCoroutine(ScanForTargetAllAround());
}
// Update is called once per frame
void Update ()
{
thisPos = new Vector2(transform.position.x, transform.position.y);
cols = Physics2D.OverlapCircleAll(thisPos, targetRange, 1 << LayerMask.NameToLayer("Unit"));
if (!target)
{
hit = Physics2D.Raycast(transform.position, Vector2.up);
Debug.DrawRay(transform.position, Vector2.up);
}
if (target)
{
var direction = target.position - transform.position;
hit = Physics2D.Raycast(transform.position, direction);
Debug.DrawRay(transform.position, direction);
float angle = Mathf.Atan2(direction.y, direction.x)*Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
IEnumerator ScanForTargetAllAround()
{
while (cols.Length > 1)
{
currentTarget = null;
float distance = Mathf.Infinity;
Collider2D currentCollider2D = cols[0];
for (int i = 0; i < cols.Length; i++)
{
currentDist = Vector2.Distance(thisPos, cols*.transform.position);*
if (currentDist < distance)
{
currentCollider2D = cols*;*
distance = currentDist;
}
}
currentTarget = currentCollider2D.gameObject.transform;
target = currentTarget;
}
yield return null;
}
}