- Home /
Unity while loop causing freezes on play
I assume this code is being read as an infinite loop, but I cannot figure out why.
I want this code to run until a GameObject is destroyed which would trigger the GameObject enemyTarget to return as null, breaking the loop.
I've force quit and rebooted my project about 20 times with new attempts but it's become clear to me that I'm missing something. Really looking for a second opinion here. This is the code. StartCoroutine("Attack");
public IEnumerator Attack()
{
while (enemyTarget != null)
{
enemyTarget.GetComponent<EnemyStats>().health -= attackDamage; //do damage
yield return new WaitForSeconds(attackSpeed);
}
LocateTargets(); //return to searching for targets
yield return null;
}
I don't see anything immediately wrong here, but there's a few things you can try so you can figure out what's going on.
Only execute the while loop a few times then break out of it
Set the attack speed to be reeaallly slow
Get rid of LocateTargets at the end and see if that makes a difference
$$anonymous$$ake sure you are only calling the coroutine ONCE
If you are using Visual Studio, you should be able to attach to Unity and debug line by line
Thanks for the reply I'm pretty confused. Going to try 1 in a bit, just as a failsafe I suppose 2 & 3 had no effect on the freezing up 4 the Coroutine is called once per enemy in the scene so I guess technically multiple times, but only once per enemy. Would that matter? 5 I'll look into setting this up, sounds pretty useful thanks
Then yeah 5 is your best bet. Even if the enemy is never destroyed Unity shouldn't freeze up as long as you have a yield return in there. I suspect something else is happening. Unity doesn't freeze up until Attack is called, right?
Answer by CmdrZin · Jan 08, 2021 at 06:43 PM
Where do you Destroy the enemyTarget so that it will be 'null'?
You also might want to move the LocateTargets() to a update method.
enemyTargets are destroyed in the Update() of EnemyStats.cs if their health <= 0
Answer by Llama_w_2Ls · Jan 08, 2021 at 09:35 PM
Where do you start the coroutine? If you start the coroutine in the update, it will start a while loop every frame, which will definitely cause a crash. @nolan_oc
I've been calling it at the end of the LocateTargets(), would that be technically an infinite loop? At Start I call LocateTargets() and if any are found it goes to Attack() and then back to LocateTargets(). I'll test this out and get back to you. Thanks for the tip