UNITY delay implementation detailed explanation
Creating delay in Unity is essential for managing game processes, sorting events, and simulation of real world behavior. Here are several methods to achieve delay:
<.> 1.
/ WaitForSeconds
WaitForSecondsRealtime
StartCoroutine
: The execution of the designated time (affected by the speed of the game). WaitForSeconds
: The execution of the specified time (not affected by the speed of the game).
WaitForSecondsRealtime
Use or
cycle: gradually increase the timer until it reaches the required value.<code class="language-C#">IEnumerator WaitForSecondsExample() { // 旋转90度 transform.Rotate(Vector3.right * 90); // 等待4秒(不受游戏速度影响) yield return new WaitForSecondsRealtime(4); // 旋转40度 transform.Rotate(Vector3.right * 40); // 等待2秒(受游戏速度影响) yield return new WaitForSeconds(2); // 旋转20度 transform.Rotate(Vector3.right * 20); }</code>
: Pay the execution of a frame.
Time.deltaTime
while
for
yield return null
: The execution was suspended until the condition was true.
<code class="language-C#">IEnumerator TimeBasedLoopExample() { // 旋转90度 transform.Rotate(Vector3.right * 90); // 等待4秒(受游戏速度影响) float timer = 0; while (timer < 4) { timer += Time.deltaTime; yield return null; } // 旋转40度 transform.Rotate(Vector3.right * 40); // 等待2秒(不受游戏速度影响) timer = 0; while (timer < 2) { timer += Time.deltaTime; yield return null; } // 旋转20度 transform.Rotate(Vector3.right * 20); }</code>
: The execution is suspended when the condition is true.
WaitUntil
WaitWhile
<示> Example:
WaitUntil
WaitWhile
: Arrange a function after the delay is delayed.
: Similar to , but the function is repeatedly called with a specified time interval.
<code class="language-C#">IEnumerator WaitUntilExample() { // 等待玩家分数达到100 yield return new WaitUntil(() => playerScore >= 100); // 加载下一关 SceneManager.LoadScene("NextLevel"); }</code>
Invoke
<.> 5. Based on
Invoke
InvokeRepeating
: each frame increases until it reaches the required value.
Invoke
Example:
<code class="language-C#">Invoke("FeedDog", 5); // 5秒后调用FeedDog() InvokeRepeating("MovePlayer", 0.5f, 0.2f); // 每0.2秒调用MovePlayer(),持续0.5秒。</code>
Solve your problem: Update()
The above is the detailed content of How to Implement Delays in Unity for Gameplay and Event Sequencing?. For more information, please follow other related articles on the PHP Chinese website!