簡體   English   中英

如何正確使用 IEnumerator?

[英]How do I properly use an IEnumerator?

我想在每次按下箭頭按鈕時延遲角色移動,這樣玩家就不能只是垃圾郵件移動,但由於某種原因,我的 IEnumerator function 不起作用,它不會等待。 我不確定我是否用錯了,因為我正在恢復團結。 如果有幫助,我正在使用版本 2019.3.14f1。

using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Threading;
using UnityEngine;

public class Movement : MonoBehaviour
{
    void Start()
    {
        transform.position = new Vector3(0, 0, 0);
    }

    void Update()
    {
        CalculateMovement();
    }

    private IEnumerator delay()
    {
        yield return new WaitForSeconds(1);
    }

    void CalculateMovement() 
    {
        if (Input.GetKey(KeyCode.UpArrow))
        {
            if (transform.position.y != 4)
            {
                StartCoroutine(delay());
                transform.position += new Vector3(0, 1, 0);
            }
        }
        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            if (transform.position.y != -4)
            {
                StartCoroutine(delay());
                transform.position += new Vector3(0, -1, 0);
            }
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            if (transform.position.x != 4)
            {
                StartCoroutine(delay());
                transform.position += new Vector3(1, 0, 0);
            }
        }
        else if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            if (transform.position.x != -4)
            {
                StartCoroutine(delay());
                transform.position += new Vector3(-1, 0, 0);
            }
        }
    }
}

協程部分就是這樣:

private IEnumerator delay()
{
    yield return new WaitForSeconds(1);
}

你不能在它上面調用StartCoroutine()然后做你的工作期望它被延遲,延遲的部分必須是你的協程的一部分,像這樣:

private IEnumerator BetterNamePlease()
{
    yield return new WaitForSeconds(1);
    transform.position += new Vector3(0, 1, 0); // use parameters here
}

StartCoroutine不會阻止代碼執行,它只是允許邏輯在執行其他邏輯時繼續。 如果您試圖阻止用戶移動,您可以使用以下內容:

public class Movement : MonoBehaviour
{
    private bool CanMove = true;

    void Start()
    {
        transform.position = new Vector3(0, 0, 0);
    }

    void Update()
    {
        CalculateMovement();
    }

    private IEnumerator DelayMovement()
    {
        CanMove = false;

        yield return new WaitForSeconds(1);
        
        CanMove = true;
    }

    void CalculateMovement() 
    {
        if (!CanMove)
        {
            return;
        }

        if (Input.GetKey(KeyCode.UpArrow))
        {
            if (transform.position.y != 4)
            {
                StartCoroutine(DelayMovement());
                transform.position += new Vector3(0, 1, 0);
            }
        }
        // etc
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM