Make enemies spawn faster with timer? (C#)

I have a timer in my 2D survival game that always counts upwards, now I spawn out a new enemy between 4 and 6 seconds with the help of IEnumerator. But I have a little problem, since I want the game to be harder and harder I want to spawn out more enemies and faster then 4 and 6 seconds the further the timer gets.

So say that the “main timer” is set at a random range between 30, 60 seconds. When this number is set I want to spawn out enemies faster, say between a random range at every 1 and 3 seconds. What is the best way to do this? I tried using an If statment but it doesn’t work that well. What do you suggest?

Here’s the code for spawning the enemies:

// Spawn a Bouncing enemy
	IEnumerator SpawnBouncingEnemy() 
	{
		//Wait 3 to 5 seconds when game starts to spawn a ball
		yield return new WaitForSeconds(Random.Range(1, 3));

		while(true)
		{
			//Calls the function to set random position
			Vector3 spawnPoint = RandomPointWithinBorders();
			
			// Show spawn location for one second
			Object marker = Instantiate(showEnemySpawn, spawnPoint, Quaternion.identity);
			yield return new WaitForSeconds(1);
			Destroy(marker);
			
			// Spawn enemy
			GameObject newEnemy = (GameObject) Instantiate(EnemyBouncingPrefab, spawnPoint, Quaternion.identity);

                    //Set the enemy to active in the List
			activeEnemies.Add(newEnemy);

                    //Wait for 4, 6 seconds before the enemy spawns again!
			yield return new WaitForSeconds(Random.Range(4, 6f));

                    //What is the best way to do this? TimerScript.timer is the "Main timer" in the game
			if(TimerScript.timer >= Random.Range(30, 60))
			{
				SpawnBouncingEnemy();
				yield return new WaitForSeconds(Random.Range(1, 1));
				countNewBouncingEnemies += 1;
				print(countNewBouncingEnemies);
			}

		}
		
	}

Why couldn’t you use Random.Range(30, 60) earlier in the code?

// Get random time.
float randTime = Random.Range(30, 60);

// Wait 3 to 5 seconds when game starts to spawn a ball
yield return new WaitForSeconds(Random.Range(1, 3));

Later, you can just type this:

if(TimerScript.timer >= randTime) {
}

This way, the random time won’t keep changing each time you spawn a new enemy.

Your timer mechanics appear to be needlesly complicated…

To start out, replace the timing system with a simple variable in any component’s Update loop, for example (pseudocode warning):

public float InitialTime = 8f;
public float timer = 8f;
public float timingModifier = 1.1f;

/// somewhere, in an Update loop in a script far away...

timer -= Time.deltaTime;

if (timer < 0)
{
    timer = (InitialTime / timingModifier);
    timingModifier += timingModifier;
}

This will make enemies spawn at first 8 seconds apart, then shorter and shorter additively.

Good mathematical solution beats 19 “if” branches :smiley: