如何 运行 命令然后计时器结束? C#

How to run command then timer is ended ? C#

我不知道如何发出命令运行然后计时器停止 这是代码:

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System.Threading;
using System;

public class introtogamescript : MonoBehaviour
{
    public class Example
    {
        public static void Main()
        {
            // Create an instance of the Example class, and start two
            // timers.
            Example ex = new Example();
            ex.StartTimer(7000);
        }

        public void StartTimer(int dueTime)
        {
            Timer t = new Timer(new TimerCallback(TimerProc));
            t.Change(dueTime, 0);
        }

        private void TimerProc(object state)
        {
            // The state object is the Timer object.
            Timer t = (Timer)state;
            t.Dispose();
            SceneManager.LoadScene(2);
        }
    }
}

感谢您的帮助。

当您启动计时器时使用 lambda 或匿名委托 - 这样您就可以将计时器关闭。

您可以这样使用 coroutines

public void  WaitAndExecute(float timer, Action callBack = null)
{
    StartCoroutine(WaitAndExecute_CR(timer,callBack));
}

IEnumerator WaitAndExecute_CR(float timer, Action callBack = null)
{
    yield return new WaitForSeconds(timer);

    if (callBack != null)
    {
        callBack();
    }
}


void Start()
{
    WaitAndExecute(5,() => {Debug.Log("This will be printed after 5 seconds");});

    WaitAndExecute(10,JustAnotherMethod);
}

void JustAnotherMethod()
{
    Debug.Log("This is another way to use callback methods");
}

你也可以使用Invoke(string methodName, float callDelay)

示例:

void SomeMethod()
{
   Invoke("OtherMethod",3.5f);
}

//It should be called 3.5 seconds after SomeMethod
void OtherMethod()
{
    print(something);
}

并且您不能调用任何参数