How do I use coroutines(?) to run a big loop without hanging the editor?

Okay so I have this function that I’m calling inside a loop, and I need it to loop several hundred, or even thousand, times without hanging the editor during the process.

Texture2D RenderImage(UnityEngine.Object o)
{
      Texture2D img = new Texture2D(128,128);
           
      //Does stuff to img

      return img;
}

So I think there is something to do with coroutines or IEnumerator that will allow me to do this but I don’t actually know what these are or how to use them

So does anyone know what I should do?
Thanks :slight_smile:

Read the above which should explain them. If you still have questions afterward, I’m sure someone can help with the details.

Hi Patrick,

Co routines are essentially routines(functions, in our case) that are run as part of the main program only when called, its vague start but once you see some scripts with co routines you will understand it.

For example: You need a object color to change when a player clicks a button. Instead checking for this condition in every frame, i.e; instead of putting the condition to check for button press in void Update(), you can put it as a co routine.
The benefit of doing so is that, you are preventing the editor from performing a redundant check always. And check only when certain condition are fulfilled.

About running the big loop, there is no problem of hanging the editor as long the function it performs is not intensive(may be rendering…)

Co routines are implemented in the Editor using following syntax:

void Update
{
//To start the coroutine
Start Coroutine(Functionname(parameter));
}


IEnumerator (function name) (parameter)
{
//your code  for checking a condition/performing a certain function goes in here

//important part is the yield return. It basically returns the control back to Unity from the script. This way you can sequence  the function  to happen only in certain  period of time.

yield return;
}

So that is basically what Co routine does and how to do it. On whether using Co routine or not is dependable on the scenario. Do not mind the long answer

Cheers

Ok thanks, I’ve just found out though that StartCoroutine() isn’t available for editor scripts, is there any alternative or work around for this?

Maybe give this package a try? I haven’t used it myself, but I’ve seen it in package manager for a while:

https://docs.unity3d.com/Packages/com.unity.editorcoroutines@0.0/manual/index.html

I actually discovered EditorUtility.DisplayProgressBar() which although doesn’t stop the editor from hanging, it shows a progress bar so at least you know it’s not frozen and can see how long it’s taken which is enough for me - thanks for the help anyway :slight_smile: