Necessary Coroutine slowing down my game

I followed a Brackeys tutorial for making an animated scene transition for my game, but instead of loading a new scene I tried making it run quite a large function to generate a level. This slowed down the loading time from 4 seconds without the coroutine to around 30 seconds with it. Is there a better way to make a loading screen transition? Without the coroutine the animation never gets the chance to play, is there a way to wait for seconds without using coroutine?

Sorry if I’ve worded this badly, I don’t really know how to describe my problem

Here’s the code in question:

private void Update()
{
if (Input.GetKey(KeyCode.Return))
{
StartCoroutine(IEIteration());
}
}
private void Iteration_()
{
TilemapClear();
BoundSet();
WallGen_();
RoomGen_();
CorridorGen_();
WallDestroy_();
PlayerSpawner_(bounds, player);

}// full generation

IEnumerator IEIteration()
{
transition.SetBool(“Start”, true);

yield return new WaitForSeconds(.9f);

Iteration_();

transition.SetBool(“Start”, false);
}

thanks for any help

if (Input.GetKey(KeyCode.Return))

This will run every frame during which the enter key is held down. Most likely more than one frame. I suspect you’re actually running your Iteration_() method multiple times. You can verify this by adding Debug.Log() statements to the method.

You can probably fix it as well by changing to :

if (Input.GetKeyDown(KeyCode.Return))
1 Like

By the way if your goal is to start an animation, and then start doing something after the animation completes, using Animation Events would be a better way to do it than using a coroutine: Unity - Manual: Use Animation Events

Alternatively you could write a StateMachineBehaviour which lets you listen to Animator state transitions:

In addition to what @PraetorBlue mentioned, you may also want to add a bool flag to prevent another coroutine from starting while one is already running.

Example:

bool coroutineRunning = false;

void Update()
{
   if(Input.GetKeyDown(KeyCode.Return) && !coroutineRunning)
   {
      StartCoroutune(SomeCoroutine());
      coroutineRunning = true;
   }
}

IEnumerator SomeCoroutine()
{
   //Do some stuff
   //yield
   //Finished

   coroutineRunning = false;
}

oh wow thank you so much I thought it was running a lot slower than it should have been for a tile based system, I can’t believe i didn’t notice the GetKey. I previously rewrote all my code to make it faster and made the same mistake twice! Animation events seem to be exactly what i need too, although my project nearly runs fast enough even now. Thank you too Vryken, I’ll add in a bool flag too, I’m not too great at using coroutines yet