Detailed explanation of Unity delay implementation
]Creating delays in Unity is essential for managing game flows, sorting events, and simulating real-world behavior. Here are a few ways to achieve delay:
1. WaitForSeconds
/WaitForSecondsRealtime
StartCoroutine
WaitForSeconds
WaitForSecondsRealtimeExample:
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);
}
2. Time-based loop
using
while or
for loop of
yield return nullExample:
IEnumerator TimeBasedLoopExample()
{
// 旋转90度
transform.Rotate(Vector3.right * 90);
// 等待4秒(受游戏速度影响)
float timer = 0;
while (timer
3.
WaitUntil/
WaitWhile Function
WaitUntil
WaitWhileExample:
IEnumerator WaitUntilExample()
{
// 等待玩家分数达到100
yield return new WaitUntil(() => playerScore >= 100);
// 加载下一关
SceneManager.LoadScene("NextLevel");
}
4.
Invoke Function
Invoke
InvokeRepeating: Similar to
InvokeExample:
Invoke("FeedDog", 5); // 5秒后调用FeedDog()
InvokeRepeating("MovePlayer", 0.5f, 0.2f); // 每0.2秒调用MovePlayer(),持续0.5秒。
]
5. Delay based on Update()
: Used to measure the time between frames.
: Check whether the timer reaches the required value and execute the necessary code.
void Update() { timer = Time.deltaTime; if (timer >= 5) { // Execute the code after 5 seconds timer = 0; FeedDog(); } }
void Update()
{
timer = Time.deltaTime;
if (timer >= 5)
{
// 5秒后执行代码
timer = 0;
FeedDog();
}
}
Solve your problem: To create a delay when displaying text in your script, you can use the following code:
IEnumerator ShowTextWithDelay() { TextUI.text = "Welcome to the Digital Wizard!"; yield return new WaitForSeconds(3f); TextUI.text = ("The highest number you can choose is "max); yield return new WaitForSeconds(3f); TextUI.text = ("The lowest number you can choose is " min); } StartCoroutine(ShowTextWithDelay());
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3