Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity Freezes-(Unity newbie)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

https://docs.unity3d.com/Manual/Coroutines.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading