溫馨提示×

c# startcoroutine在協(xié)程中實(shí)現(xiàn)延時(shí)操作的技巧

c#
小樊
87
2024-08-13 15:24:38
欄目: 編程語言

在C#中使用StartCoroutine來實(shí)現(xiàn)延時(shí)操作的技巧是通過創(chuàng)建一個(gè)協(xié)程函數(shù)來實(shí)現(xiàn)延時(shí)操作。以下是一個(gè)示例代碼:

using System.Collections;
using UnityEngine;

public class DelayExample : MonoBehaviour
{
    private void Start()
    {
        StartCoroutine(DelayedAction());
    }

    private IEnumerator DelayedAction()
    {
        Debug.Log("Start of delayed action");

        yield return new WaitForSeconds(2);

        Debug.Log("Delayed action completed");
    }
}

在上面的代碼中,我們創(chuàng)建了一個(gè)DelayExample類,并在Start方法中調(diào)用StartCoroutine來啟動一個(gè)協(xié)程函數(shù)DelayedAction。在DelayedAction函數(shù)中,我們使用yield return new WaitForSeconds來實(shí)現(xiàn)一個(gè)延時(shí)操作,這里延時(shí)2秒后打印"Delayed action completed"。這樣就實(shí)現(xiàn)了在協(xié)程中進(jìn)行延時(shí)操作的技巧。

0