Home > Backend Development > C++ > How to Simply Make a Script Wait/Sleep in Unity?

How to Simply Make a Script Wait/Sleep in Unity?

DDD
Release: 2025-01-31 13:11:09
Original
859 people have browsed it

How to Simply Make a Script Wait/Sleep in Unity?

UNITY script waiting/suspension of several methods

Unity provides a variety of methods to wait or pause of scripts. This article will introduce several commonly used methods:

<.> 1. Use correction and

WaitForSeconds This is the simplest and direct method. Put the code you need to wait in the coroutine function, and use the specified waiting time. Remember, the coroutine function needs to be started with

.

WaitForSeconds StartCoroutine(yourFunction) <.> 2. Use correction and

<code class="language-C#">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);
}</code>
Copy after login

The difference between and WaitForSecondsRealtime is that it uses an unproof time to wait. Even if is suspended,

will not be affected.

WaitForSecondsRealtime WaitForSeconds <.> 3. Use coroutine and Time.timeScale Show waiting time WaitForSecondsRealtime

<code class="language-C#">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);
}</code>
Copy after login
This method is suitable for scenes that need to display waiting time, such as timer. It also allows interrupt operations during the waiting process.

Time.deltaTime Simple version, separate the timer into an independent coroutine:

<.> 4. Use correction and

Function
<code class="language-C#">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;
    }
    // ... 剩余代码 ...
}</code>
Copy after login

Waiting for specific conditions to meet. For example, wait for the player score to reach 100 points before loading the next level.
<code class="language-C#">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;
    }
}</code>
Copy after login

<.> 5. Use correction and WaitUntil Function

Waiting for specific conditions is not met. For example, wait for the player to press the ESC key and exit the game.

<code class="language-C#">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);
}</code>
Copy after login

<.> 6. Use Function WaitWhile

Delay calling function.

<code class="language-C#">private void Start()
{
    StartCoroutine(InputWaiter());
}

private IEnumerator InputWaiter()
{
    Debug.Log("等待按下 Escape 键");
    yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape));
    Debug.Log("按下 Escape 键。退出应用程序");
    Quit();
}

// ... (Quit 函数) ...</code>
Copy after login
<.> 7. Use

function and Invoke

Similar method 3, but do not use coroutines. This will frequently call, low efficiency, not recommended for long -term waiting.

which method to choose depends on the specific application scenario. For simple latency, or
<code class="language-C#">private void Start()
{
    Invoke("FeedDog", 5);
    Debug.Log("5 秒后喂狗");
}

private void FeedDog()
{
    Debug.Log("现在喂狗");
}</code>
Copy after login
is sufficient; for the scenes that require conditions to judge or display the waiting time, you need to use coroutines and

, or Update(). Avoid waiting for a long time in Time.deltaTime.

The above is the detailed content of How to Simply Make a Script Wait/Sleep in Unity?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template