Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase an integer every specified seconds c#

You will see under the void start function the currentWave. I want it to increment by 1 every 20 seconds. but not sure where and how to go about doing so. Below you will see my declared variables. I have left out the other section of code as it is not necessary for what I need.

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

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

Above is my declared variables, and below is my stary function with currentWave set to 1, which is the integer I want to change every 20 seconds.


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

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

I used my update function to get the current "running time" of the program.

like image 399
Kyle Westran Avatar asked Dec 12 '25 02:12

Kyle Westran


1 Answers

Use a coroutine:

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++;
    }
}

if you want it to increment immediately, put currentWave++ before yield return waiter;:

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

Then, you can stop it with StopCoroutine(waveIncrementer);

like image 115
Ruzihm Avatar answered Dec 13 '25 17:12

Ruzihm