- Home /
Can't seem to do a coroutine loop?
Hello everyone! I am attempting to do a proximity check in which a coroutine checks if there are any circles nearby. Here is my attempt:
bool ProximityCheck()
{
circleObjects = GameObject.FindGameObjectsWithTag("Circle"); //looking for all the circles
for (int i = 0; i < circleObjects.Length; i++)
{
if (Vector3.Distance(player.transform.position, circleObjects[i].transform.position) < maxDistanceBPAC) //checking if they are far away
{
print("returned true");
return true;
}
}
print("returned false");
return false;
}
IEnumerator DoCheck()
{
print("DIDCHECK");
if(ProximityCheck() == false)
{
cs.SpawnCircles(); //spawn circles if the proximity check returns false (if there are no circles nearby)
print("Proximity check returned false, spawning");
}
yield return new WaitForSeconds(1f);
StartCoroutine(DoCheck()); //call the same coroutine again to do the check every second
}
The problem arises when the coroutine simply stops running (the print("DID CHECK")
doesn't run). It seems to stop running when there are no circles nearby. Would anyone be able to point out the flaw in my script? I would appreciate it a lot! Thank you.
Answer by pigaroos · Dec 13, 2019 at 02:43 AM
Alright, the problem was that the script in which these functions were running in were in the circles themselves (which get destroyed) so these functions were getting destroyed with them. I just created an empty game object and another script and put these in there, which resulted in them working.
Moral of the story, check if your scripts are being destroyed if your Debug.Logs stop out of nowhere. Oh, and to the guy that deleted his answer: I was going to accept it anyway lol
Great you solved your issue. However I strongly recommend to not constantly restarting the same coroutine. Just use an infinite loop. Starting a coroutine creates garbage and has overhead. Just keep the coroutine running.
IEnumerator DoCheck()
{
while (true)
{
if(ProximityCheck() == false)
{
cs.SpawnCircles(); //spawn circles if the proximity check returns false (if there are no circles nearby)
}
yield return new WaitForSeconds(1f);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
While loop ignores conditions in coroutine 1 Answer
Distribute terrain in zones 3 Answers
Coroutine For Loop Will Not End 1 Answer
Trouble with Iterative Coroutine 1 Answer