Unity脚本等待/暂停的几种方法
Unity 提供多种实现脚本等待或暂停的方法,本文将介绍几种常用的方式:
1. 使用协程和WaitForSeconds
这是最简单直接的方法。将需要等待的代码放入协程函数中,使用WaitForSeconds
指定等待时间。 记住,协程函数需要用StartCoroutine(yourFunction)
启动。
private void Start() { StartCoroutine(Waiter()); } private IEnumerator Waiter() { // 旋转 90 度 transform.Rotate(new Vector3(90, 0, 0), Space.World); // 等待 4 秒 yield return new WaitForSeconds(4); // 旋转 40 度 transform.Rotate(new Vector3(40, 0, 0), Space.World); // 等待 2 秒 yield return new WaitForSeconds(2); // 旋转 20 度 transform.Rotate(new Vector3(20, 0, 0), Space.World); }
2. 使用协程和WaitForSecondsRealtime
WaitForSecondsRealtime
与WaitForSeconds
的区别在于,它使用未缩放的时间进行等待,即使Time.timeScale
被暂停,WaitForSecondsRealtime
也不会受到影响。
private void Start() { StartCoroutine(WaiterRealtime()); } private IEnumerator WaiterRealtime() { // 旋转 90 度 transform.Rotate(new Vector3(90, 0, 0), Space.World); // 等待 4 秒 (不受 Time.timeScale 影响) yield return new WaitForSecondsRealtime(4); // 旋转 40 度 transform.Rotate(new Vector3(40, 0, 0), Space.World); // 等待 2 秒 (不受 Time.timeScale 影响) yield return new WaitForSecondsRealtime(2); // 旋转 20 度 transform.Rotate(new Vector3(20, 0, 0), Space.World); }
3. 使用协程和Time.deltaTime
显示等待时间
此方法适合需要显示等待时间的场景,例如计时器。 它也允许在等待过程中中断操作。
private bool quit = false; private void Start() { StartCoroutine(WaiterWithTimer()); } private IEnumerator WaiterWithTimer() { float counter = 0; float waitTime = 4; while (counter < waitTime) { counter += Time.deltaTime; Debug.Log("已等待时间:" + counter + " 秒"); if (quit) yield break; yield return null; } // ... 剩余代码 ... }
更简洁的版本,将计时器部分分离成独立协程:
private bool quit = false; // ... (WaiterWithTimer 函数) ... private IEnumerator WaitTimer(float waitTime) { float counter = 0; while (counter < waitTime) { counter += Time.deltaTime; Debug.Log("已等待时间:" + counter + " 秒"); if (quit) yield break; yield return null; } }
4. 使用协程和WaitUntil
函数
等待特定条件满足。例如,等待玩家分数达到100分再加载下一关。
private float playerScore = 0; private int nextScene = 0; private void Start() { StartCoroutine(SceneLoader()); } private IEnumerator SceneLoader() { Debug.Log("等待玩家分数达到 >= 10"); yield return new WaitUntil(() => playerScore >= 10); Debug.Log("玩家分数 >= 10。加载下一关"); nextScene++; SceneManager.LoadScene(nextScene); }
5. 使用协程和WaitWhile
函数
等待特定条件不满足。例如,等待玩家按下Esc键再退出游戏。
private void Start() { StartCoroutine(InputWaiter()); } private IEnumerator InputWaiter() { Debug.Log("等待按下 Escape 键"); yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape)); Debug.Log("按下 Escape 键。退出应用程序"); Quit(); } // ... (Quit 函数) ...
6. 使用Invoke
函数
延迟调用函数。
private void Start() { Invoke("FeedDog", 5); Debug.Log("5 秒后喂狗"); } private void FeedDog() { Debug.Log("现在喂狗"); }
7. 使用Update()
函数和Time.deltaTime
类似方法3,但不使用协程。 这会频繁调用,效率较低,不推荐用于长时间等待。
选择哪种方法取决于具体的应用场景。 对于简单的延迟,WaitForSeconds
或Invoke
足够;对于需要条件判断或显示等待时间的场景,则需要使用协程和WaitUntil
、WaitWhile
或Time.deltaTime
。 避免在Update()
中进行长时间等待。
以上是如何简单地使脚本等待/睡觉?的详细内容。更多信息请关注PHP中文网其他相关文章!