UNITY script delay implementation method Detailed explanation
In the development of unity games, insertion delays are often needed to be inserted between game events or movements. This article will introduce several methods to implement the UNITY script delay, from simple to advanced.
<.> 1. Use coroutine and WaitForseconds
The easiest way is to use corporate and . Examples as follows:
<.> 2. Use coroutine and WaitForsecondsRealtime WaitForSeconds
<code class="language-C#">IEnumerator waiter() { // 等待4秒 yield return new WaitForSeconds(4); // 延迟后执行的操作 } StartCoroutine(waiter());</code>
.
<.> 3. The coroutine based on time tracking WaitForSeconds
Time.timeScale
If a timer needs to be displayed, you can use this method.
<code class="language-C#">IEnumerator waiter() { // 等待4秒真实时间 yield return new WaitForSecondsRealtime(4); // 延迟后执行的操作 }</code>
<.> 4. Use the Waituntil coroutine
Parking execution until it meets the specified conditions.
<code class="language-C#">IEnumerator waiter() { float elapsedTime = 0; float waitTime = 4; while (elapsedTime < waitTime) { elapsedTime += Time.deltaTime; // 更新计时器显示 yield return null; } // 延迟后执行的操作 }</code>
As long as the specified conditions are true, the execution is suspended.
<.> 6. Use the INVOKE function
<code class="language-C#">IEnumerator waiter() { Debug.Log("等待玩家分数达到或超过100"); yield return new WaitUntil(() => playerScore >= 100); // 条件满足后执行的操作 }</code>
Arrange a function after the delay is specified.
<.> 7. Use the update () function and time.Deltatime
<code class="language-C#">IEnumerator waiter() { Debug.Log("等待退出按钮按下"); yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape)); // 条件为假(按下退出按钮)后执行的操作 }</code>
Use cumulative time and trigger operation when reaching the threshold.
Solution for specific problems
<code class="language-C#">Invoke("feedDog", 5); // 5秒后调用feedDog()函数</code>
The above is the detailed content of How to Implement Delays in Unity Scripts?. For more information, please follow other related articles on the PHP Chinese website!