每隔指定时间在C#中增加一个整数

3

在void start函数下,您会看到currentWave变量。我希望它每20秒增加1,但不确定何时以及如何实现。下面是我声明的变量。我省略了代码的其他部分,因为这不是我需要的。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Spawner : MonoBehaviour
{
    private int currentWave;
    private float startTime;
    private float currentTime;

上面是我声明的变量,下面是我的启动函数,其中currentWave设置为1,这是我想每20秒更改的整数。


    void Start()
    {
        currentWave = 0;
        startTime = Time.time;
        StartCoroutine(SpawnEnemy(TimeFrame[currentWave]));
    }

    void Update()
    {
        currentTime = Time.time - startTime;
        Debug.Log(currentTime);
    }
}

我使用了更新函数来获取程序的当前“运行时间”。

你可以使用 Time.DeltaTime 来测量时间。否则,FixedUpdate 在每帧固定时间运行。 - vvilin
3个回答

1
使用协程:
private IEnumerator waveIncrementer;

void Start()
{
    currentWave = 0;
    startTime = Time.time;
    StartCoroutine(SpawnEnemy(TimeFrame[currentWave]));
    waveIncrementer = IncrementWave();
    StartCoroutine(waveIncrementer);
}

IEnumerator IncrementWave() 
{
    WaitForSeconds waiter = new WaitForSeconds(20f);
    while (true)
    {
        yield return waiter;
        currentWave++;
    }
}

如果你希望立即增加它,请在 yield return waiter; 之前放置 currentWave++
IEnumerator IncrementWave() 
{
    WaitForSeconds waiter = new WaitForSeconds(20f);
    while (true)
    {
        currentWave++;
        yield return waiter;
    }
}

然后,您可以使用StopCoroutine(waveIncrementer);来停止它。

我得到了一个错误 - 无法隐式地将类型“UnityEngine.WaitForSeconds”转换为“System.Collections.IEnumerator”Assembly-CShar- 在这一行上 - IEnumerator waiter = new WaitForSeconds(20f); - Kyle Westran
@KyleWestran 哦,是啊,我太傻了。试试 WaitForSeconds waiter = new WaitForSeconds(20f); - Ruzihm

0

不,我的游戏对象在一个数组中,当前波是我用来切换到下一个数组的值。 - Kyle Westran
没有你的其余代码,很难理解你想做什么。但是从我所了解的情况来看,您有一个协程生成敌人,这些敌人依赖于索引。那个索引是您需要每20秒增加的索引。您可以通过引用传递int(https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref)在调用重复协程上轻松更新int,该int将每20秒更新一次。我认为这不是最干净的方法,但是没有您的其余代码,这是我能想到的最好的方法。 - Pedro Azevedo

0

你不需要每帧都更新它。只需在需要时计算它。将该字段更改为属性,并返回计算值。

public class Spawner : MonoBehaviour
{
    private float startTime;
    private float CurrentTime
    {
        get
        {
            return Time.time - startTime;
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接