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中文網其他相關文章!