如何运行命令,然后定时器结束?c#
本文关键字:定时器 然后 结束 命令 何运行 运行 | 更新日期: 2023-09-27 18:04:46
我不知道如何使命令运行,然后计时器停止下面是代码:
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);
}
}
}
谢谢你的帮助
您可以这样使用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");
}
当你启动计时器时,使用lambdas或匿名委托-这样你就可以将计时器作为闭包。
您也可以使用Invoke(string methodName, float callDelay)
的例子:
void SomeMethod()
{
Invoke("OtherMethod",3.5f);
}
//It should be called 3.5 seconds after SomeMethod
void OtherMethod()
{
print(something);
}
不能调用任何参数