What is Unity Coroutine? How is it Used? (2023)

    09.01.2023
    589
    What is Unity Coroutine? How is it Used? (2023)

    What Is Unity Coroutine? How is it used? we’ll be answering your questions. Unity Coroutine has the function structure we know. We’re going to talk about coroutines, which are a popular and very powerful feature of unity. Through coroutines, for example, you can delay the running of the code for a few seconds, wait for a certain process to finish, or spread the process for a few seconds.

    What are Unity Coroutines? Coroutines tutorial.

    What is Unity Coroutine?

    Unity Coroutine has a functional structure that we know, the only distinction is that we can perform blocking operations within these functions. When we consider the Update or FixedUpdate functions, they are the functions that are called in each frame. When we do this with Coroutine functions, instead of constantly calling, it goes on hold for the time we give and allows our commands to work.

    They are ideal for operations such as turning the lights on and off at certain intervals, ensuring that the gun is fired at certain intervals. When we look at its structure, it can look similar to running out of the main thread, creating a kind of fitting-parallel flow. But it has nothing to do with multi-threading. It is useful to know this from the beginning and not mix it up.

    What are Unity 3D Coroutines? Unity C# Coroutines.
    What are Unity 3D Coroutines? Unity C# Coroutines.

    In a similar form that I mentioned, the functions that allow you to work on the mainstream are actually. And they’re connected to game objects. In other words, the coroutine, opened with a script on the game object, will disappear as soon as the object disappears. On the other hand, while a unity coroutine is running, it will continue to work until the function is complete, even if we deactivate the component it was found in.

    So what got us to create this waiting case? But here we just need to use IEnumerator as a return type. In functions other than Void-type functions, we usually need to return an asset. Here, when we return the value with the IEnumaretor type, we say to the system, “let me see, you’ll wait this long.” But don’t be confused, we don’t return a figure value, etc. when we say Wait here. We return a variable of type IEnumerator.

    Use Of Unity Coroutine

    Unity Coroutines are also originally functions, and they are no different from the flat functions you are familiar with, except for a few small differences:

    • Coroutines must return IEnumerator. To access this interface, per your code using System.Collections; You need to add the line. But as you may have noticed, Unity automatically adds this line to newly opened scripts, so coroutines are mostly used in Unity.
    • Coroutines must be called with StartCoroutine function (otherwise coroutine will not work)
    • At least one yield return statement must be used inside the coroutine.

    For example, let’s take a look at the code at the bottom:

    void Start()
    {
    Debug.Log("Start start");
    StartCoroutine( CoroutineTest() ); // Initialize the CoroutineTest coroutine
    Debug.Log("Start finish");
    }

    IEnumerator CoroutineTest()
    {
    Debug.Log( "First frame" );
    yield return null; // wait for 1 frame
    Debug.Log( "Second frame" );
    }

    As you can imagine, our coroutine in this code is the CoroutineTest function. The  yield return null;  a line that we write in this coroutine allows the coroutine to wait there for 1 frame. Coroutines act independently of the functions that call them. In other words, the fact that we hold the CoroutineTest function at 1 frame does not mean that we hold the Start function at 1 frame. While coroutinetest waits for 1 frame, Start continues to run in its smooth course. So the output of this program is as follows:

    • Start/Start
    • First frame
    • Start finish
    • The second frame

    Now let’s take a look at this coroutine:

    IEnumerator CoroutineTest()
    {
    Debug.Log( "Time: " + Time.time );
    yield return new WaitForSeconds( 1.5f ); // wait 1.5 seconds
    Debug.Log( "Time: " + Time.time );
    }

    As you can see, you can hold a coroutine for a certain period through the WaitForSeconds function. Here is the point that you need to pay attention to, the Time of this period. He is affiliated with timescale. So if you took the game into slow motion by making a timescale of 0.5, this code waits 3 seconds, not 1.5 seconds. If you want to wait a few seconds independently of the timescale, you can use the WaitForSecondsRealtime function.

    In the following example, you can download a good photo from the internet using the WWW class and assign this image to the material of the object to which the script is assigned. You also see that a coroutine can also take parameters. If you make a WWW object yield return, your code waits for that WWW operation to finish (in this example, the image will come down from the internet). Don’t get too hung up on it, since the phrase used in the code has nothing to do with the coroutines.

    Unity Coroutine WaitForSeconds
    Unity Coroutine WaitForSeconds

    Note: If you want to use UnityWebRequest instead of WWW, you can return the object returned when you call the Send/SendWebRequest function of the UnityWebRequest object to wait for the operation to finish.

    For example, the following code serves to move the object to which the code is assigned from its current position to 10,10,10 in 3 seconds:

    Unity Coroutine UnityWebRequest
    Unity Coroutine UnityWebRequest

    If you want, you can start another coroutine from inside a coroutine with StartCoroutine again, and to wait for this coroutine to end, you can make it yield a return (if you don’t want to wait, you don’t have to yield a return):

    Unity StartCoroutine
    Unity StartCoroutine

    So what are you going to do if you want to stop a coroutine that’s working? Here, the functions StopCoroutine and StopAllCoroutines come into play. The StopAllCoroutines function allows you to stop all coroutines started with StartCoroutine in this object, while the StopCoroutine function allows you to stop a certain coroutine entered as a parameter. For this, you need to keep the coroutine you want to stop in a coroutine variable. For example:

    Unity StopCoroutine
    Unity StopCoroutine

    Reuse Waitforseconds Objects

    Yield return new WaitForSeconds(1f);” or “yield return new WaitForSecondsRealtime(1f);” are mostly used in coroutines in unity. However, each time these lines are run, memory is allocated for a new WaitForSeconds object (allocation). To avoid this, I wrote a simple script that uses the object pool pattern.

    What you need to do is to install a new C# script called BetterWaitForSeconds in your project and replace the content of the script with the following code: GitHub Link

    Then in your coroutines yield return “BetterWaitForSeconds.Wait(1f);” or “yield return BetterWaitForSeconds.WaitRealtime(1f);” By using lines, you can work with WaitForSeconds objects that automatically take advantage of the object pool.

    Unity Coroutine Return Values

    For Unity Coroutine return values, Unity already offers us options. I’ll mention them in the continuation of the article and create code examples for you. As you can see in the previous examples, you can use these commands after typing “yield return new“. You don’t need to use the word “new” just before null and break.

    WaitForEndOfFrame

    WaitForEndOfFrame when we use this value allows us to hold our commands until the end of the frame. But what we need to pay attention to here is that the Square will eventually take place as stated in the command. If you want to do a treat in an update or late update and then test it in your Coroutine function, this method may be useful.

    WaitForFixedUpdate

    Allows us to hold our commands until the next Fixed Update function is called.

    WaitForSeconds

    It allows us to wait as many seconds as we specify the in-game time. It is influenced by the timescale value. But it is worth noting that this test is not performed very strictly. For example, when we ask it to wait 5 seconds, it will work not when it is exactly 5 seconds, but when it has passed 5 in a very small format.

    WaitForSecondsRealtime

    WaitForSecondsRealtime is a structure that allows us to value in seconds compared to real-time, regardless of game time.

    WaitUntil

    wait until this is the code that allows us to wait until the condition that we specify is met. For example, we can say keep waiting until the bullet==0.

    WaitWhile

    It is the code that gets us to wait as long as the situation we specify is provided. The while Cycle Works in its logic.

    Null

    Null the working logic is similar to the WaitForEndOfFrame function. But the difference between them is related to the order in which they are run. when we give a null value, it will work as soon as the update function is played in the next frame. So he won’t wait for the end of the frame.

    Break

    Break you can use it to stop the coroutine process in any situation, especially in processes where you use cycles.

    Thank you for reading the article. For more detailed unity information: What is Unity 3D? Detailed Unity Guide

    unity coroutine return value
    unity check if coroutine is running
    unity coroutine waitforseconds
    unity yield break
    unity wait for coroutine to finish
    unity yield return
    unity coroutine timer
    unity coroutine loop
     
    AUTHOR INFO
    Welcome to Gameplay Developer, your number one source for all things related to 30 Rose Lane, Henderson, NC... We're dedicated to giving you the very best of 30 Rose Lane, Henderson, NC. with a focus on quality and real-world problem solutions.
    COMMENTS

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    No comments yet, be the first by filling the form.