How To Add A Delay In Unity
Most game developers take virtually likely asked themselves "How do you lot actually create a delay before doing a sure action?".
Trust u.s., we've asked ourselves this question as well.
But how do yous actually make a time delay before doing an action? The respond is very unproblematic. Information technology's by using Coroutines or Invoke!
But how do you actually utilize information technology?
In this tutorial, we're gonna be taking a look at how to create a Practise Afterward Filibuster function that you can employ for something like spawning monsters afterwards a filibuster, triggering a cutscene after a delay, or attack afterward a delay.
But we'll make it as simple as possible so you get the thought of how to use delays in your game.
Getting Started
For this tutorial, we don't need to utilize that many game objects merely nosotros do need at least ane cube for testing the following script.
So open your Unity, create a new Scene, and add a new 3D game object like Cube.
How To Create a Delay With Coroutines
One of the easiest ways to create a delay is by using a coroutine.
What is a coroutine?
According to Unity's official documentation, a coroutine is a function that has the ability to stop or suspension an execution. Meaning that anything after the coroutine will non be executed unless the coroutine is washed processing.
At present how does a coroutine works in Unity?
A coroutine works by using an IEnumerator
function. With this, y'all will be able to employ the yield
statement and the WaitForSeconds()
function to cease your script for a sure period of time.
In one case you accept created the office, you will then need to utilise the StartCoroutine()
function to trigger your IEnumarator function.
So with that said, allow's create a new C# script, name it ChangeColorAfterDelay.cs and re-create the following lawmaking
using Organisation.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeColorAfterDelay : MonoBehaviour { private Renderer _renderer; [SerializeField] private bladder _time = 3f; // First is called before the kickoff frame update void Start() { _renderer = GetComponent<Renderer>(); StartCoroutine(ChangeColor(_time)); } public IEnumerator ChangeColor(float t) { yield return new WaitForSeconds(t); _renderer.material.color = Color.reddish; } }
Code language: HTML, XML ( xml )
For this code, nosotros first created a Renderer variable.
Then, correct within the Showtime()
function, we used the GetComponent
to go the renderer component from the game object that is attached to this script.
Later getting the component, nosotros used the StartCoroutine()
function to trigger the WaitForSeconds()
function.
Note that you can as well laissez passer the proper noun of the IEnumerator
function equally a string statement for StartCoroutine()
like this:
StartCoroutine("ChangeColor");
Code language: JavaScript ( javascript )
Next, we created the IEnumerator
part and gave it a float
parameter which nosotros're going to use for the WaitForSeconds()
role as the fourth dimension for waiting. And so for instance, nosotros have a value of 3f
in our _time
variable, the function will stop for but three seconds.
After waiting, we then modify the color of the cube to red.
If you save this script and apply this script to a game object like a cube. You should be able to see its colour alter after 3 seconds.
How To Create a Delay Without Coroutines
Now, we are able to create a delay using coroutines, simply how tin we practice information technology without using coroutines?
The respond is actually very uncomplicated and shorter compared to the previous i. It's past using the Invoke()
office.
Let's try it.
Open the same C# script and copy the following code:
using System.Collections; using System.Collections.Generic; using UnityEngine; public grade ChangeColorAfterDelay : MonoBehaviour { private Renderer _renderer; [SerializeField] individual bladder _time = 3f; // Start is chosen earlier the first frame update void Start() { _renderer = GetComponent<Renderer>(); Invoke("ChangeColor", _time); } public void ChangeColor() { _renderer.textile.color = Colour.red; } }
Code language: HTML, XML ( xml )
Unfortunately, Invoke is not maintainable as coroutines and then if you are making a circuitous scenario where yous demand to each second, nosotros suggest going for coroutines instead of Invoke.
If you run the game, yous should be able to see the very same result as the previous one.
Invoke vs Coroutine
Now that nosotros have learned the 2 means of how to create delay functions in Unity, permit'southward talk about which one is better to use and which one is not.
Invoke is great and it does its job. Nevertheless, if nosotros talk almost maintainability, Invoke is not as maintainable as coroutines. Invoke runs merely in ane fourth dimension. You call Invoke function and it will wait a couple of seconds and information technology's washed.
Merely with Coroutines, yous are able to dispense each second that passes within the coroutine.
Let's give you an example.
Y'all create a coroutine and it waits for 5 seconds.
When you run the game, the coroutine starts counting. 5… iv… and subsequently reaching 3 seconds, you execute a function. Then the coroutine volition go on counting until information technology reaches 0 seconds.
using System.Collections; using Arrangement.Collections.Generic; using UnityEngine; public class ChangeColorAfterDelay : MonoBehaviour { private Renderer _renderer; [SerializeField] private float _time = 3f; // Start is called before the first frame update void Start() { _renderer = GetComponent<Renderer>(); StartCoroutine(ChangeColor(_time)); } public IEnumerator ChangeColor(bladder t) { while (t > 0) { if (t == 3f) Debug.Log("We reached iii seconds!"); else Debug.Log(t); t--; yield render new WaitForSeconds(1f); } _renderer.textile.color = Colour.red; } }
Lawmaking language: HTML, XML ( xml )
With this, you have much control with what is happening in your game.
If you try the script higher up, you should have the following output.
Conclusion
Making delays in Unity can be a boring task simply with coroutines and invoke, we do promise that you are able to create the delay part that meets the requirement of your game.
If you're looking for more than just coroutines and delays, try Delay, Invoke, Repeat. It's a very awesome plugin that allows you lot to create delays using not simply time but also weather condition.
Disclosure: This article may incorporate affiliate links, which means nosotros may receive a commission if you click a link and purchase something that we take recommended.
How To Add A Delay In Unity,
Source: https://weeklyhow.com/unity-delay-function/
Posted by: rubioalwass.blogspot.com
0 Response to "How To Add A Delay In Unity"
Post a Comment