- Home /
Coroutine not working correctly?
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[i].transform.position);
if (currentDist < distance)
{
currentCollider2D = cols[i];
distance = currentDist;
}
}
currentTarget = currentCollider2D.gameObject.transform;
target = currentTarget;
}
yield return null;
}
}
Answer by yashpal · Nov 29, 2014 at 04:42 AM
@kamuzai1226, I think you wan to call ScanForTargetAllAround Coroutine many times. but here you just call StartCoroutine(ScanForTargetAllAround()) in Start so it called only one time. so put it on Update() or inside Coroutine so it called itself when it complete.
But do you think this would be okay with 500 of these units at once? $$anonymous$$y understanding of the coroutine is that it keeps running the method, no?
@kamuzai1226, coroutine is not running infinite. acoording to documentation are use for fade like things. So you don't need to make coroutine you can use function and called form Update() in your script. Here is a basic use of coroutine. Feel free to comment if you have question.
Your answer
Follow this Question
Related Questions
OverlapCircle funcion to avoid Gameobject creation if Collision ? 1 Answer
Ball bounces in the wrong direction 1 Answer
How do I make bullets pass through some game objects? 1 Answer
Verification Errors on creating a PolygonCollider2D from a contour trace 1 Answer
Unity 5: RigidBody or No RigidBody? 1 Answer