I'm totally newbie in Unity and C#, and will apprecaite your Help.
i'm trying to make tower Defense Game,with help of Tutorial, but it seems to be a Problem with while under my Game Loop,it will freez each time i use While
. and something else that i notice is EnemyIDsToSummon.Count
is whole the time 0
.
here you can see my GameLoop:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameLoopManager : MonoBehaviour
{
private static Queue<int> EnemyIDsToSummon;
public bool LoopShouldEnd;
private void Start()
{
EnemyIDsToSummon= new Queue<int>();
EntitySummoner.Init();
StartCoroutine(GameLoop());
InvokeRepeating("SummonTest", 0f, 1f);
}
void SummonTest(){
EnqueueEnemyIDToSummon(1);
}
IEnumerator GameLoop(){
while(LoopShouldEnd==false){
//Spawn Enemies
if(EnemyIDsToSummon.Count>0)
{
for(int i=0;i<EnemyIDsToSummon.Count;i ){
EntitySummoner.SummonEnemy(EnemyIDsToSummon.Dequeue());
}
}
//Spawn Towers
//Move Enemies
//Tick Towers
//Apply Effects
//Damge Enemies
//Remove Enemies
// remove Towers
}
yield return null;
}
public static void EnqueueEnemyIDToSummon(int ID){
EnemyIDsToSummon.Enqueue(ID);
}
}
and here is the tutorial i've used:
https://www.youtube.com/watch?v=-Pj5o5I_Wl4&t=1263s
CodePudding user response:
You've written a Unity coroutine GameLoop
, which has a while loop in it.
The engine will enter the while loop and never leave, because nothing sets LoopShouldEnd
to true
, or breaks out of the loop.
Usually, you'd fix this by yielding from the coroutine (yield return null
) from inside the while loop, and setting LoopShouldEnd
to false
on the frame you want it to stop, or ending the while loop once you're done spawning inside that frame (you can break
to end it immediately)
When the yield is outside the while loop, it will only happen after the while loop finishes, which is never, so no other code runs and the editor freezes.
Some useful documentation on coroutines: