如何使用 C# 中的计时器使动作每 x 秒重复一次?

1 c# timer unity-game-engine

我\xc2\xb4m 试图在Unity 的游戏中编写一个功能,允许玩家回到5 秒前的位置,所以我希望每5 秒,保存玩家\xc2\xb4s 坐标以返回到如果您按下某个键,则会显示它们。

\n\n

我唯一不知道的就是与时间有关的一切。我看到了使用计时器的指南,但我不明白\xc2\xb4到底是什么,有人可以帮忙吗?

\n

Kac*_*per 7

如果您使用 Unity,那么编写与时间相关的操作的最简单方法就是协程。您只需调用StartCoroutine然后使用即可yield return new WaitForSecondsRealtime(5f)。使用 .NET 计时器也是一种选择,但在大多数情况下,在 Unity 中开发游戏时我不会推荐它。

例如,如果您定义这样的方法

IEnumerator MyCoroutine()
{
    yield return new WaitForSeconds(5f);
    //code here will execute after 5 seconds
}
Run Code Online (Sandbox Code Playgroud)

您稍后可以这样称呼它

StartCoroutine(MyCoroutine)
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用Time.deltaTime内部Update方法。使用这种方法,您的代码可能看起来像这样

float timePassed = 0f;
void Update()
{
    timePassed += Time.deltaTime;
    if(timePassed > 5f)
    {
        //do something
        timePassed = 0f;
    } 
}
Run Code Online (Sandbox Code Playgroud)

如果你真的不希望你的代码是 Unity 特定的,你必须在System.Threading.Timer和 之间进行选择System.Timers.Timer