Best way to spawn enemies based on time

I have been looking for a solution to this, and I apologise if this has been answered before.

I am working on a Vertical Style Scrolling shooter, for instance 1942 imagealt text

The plan is to spawn enemies in waves after a certain amount of time. I have been trying to do this in different ways. My knowledge of Unity is limited as I am new, and have only been working through the basics thus far.

I have been trying to use this:

void Start () {

	spawnTimer = 7.0f;
}

	void Update () {

		timer += Time.deltaTime;
		if(timer==spawnTimer){
			print("7 secs passed");
			Spawner(1.2f);
		}
	}
	void Spawner(float whichNPC){

		if(whichNPC == 1.2f){
			SendMessage("SpawnNPC1M");
			totalNPCSpawned += 5;
			print(totalNPCSpawned);
		}

The problem seems to arise with using “if(timer==spawnTimer){” I guess this is due to the time not being in exact values. I know its possible to use > but the plan is to use the variable “timer” again, once further time has expired, and to stop it from calling the “Spawner” function over and over again causing multiple enemies to keep spawning.

Hope this makes any sense?

Is it perhaps better to use WaitForSeconds each time?

Thanks in advance.

You are correct in why it’s not triggering. Comparing floats with == can often miss. Even when manually changing the values (like adding 0.1f), trying to compare to 1.0f can still miss due to rounding issues. Positions are also common to being just slightly off.

For this situation, there are a few ways I can think off of the top of my head. First is to use if(timer >= spawnTimer), and reset timer to 0 on trigger. You can also adjust spawnTimer if you want different times between waves.

using UnityEngine;
using System.Collections;

public class SpawnWaves : MonoBehaviour
{
	float spawnTimer = 7f;
	float timer = 0f;
	int waveNumber = 0;
	
	void Update ()
	{
		timer += Time.deltaTime;
		if(timer >= spawnTimer)
		{
			Spawner();
		}
	}

	void Spawner()
	{
		//Switches are cleaner than using many ifs when checking one variable.
		switch(waveNumber)
		{
		case 0://If waveNumber == 0
			//Spawn first wave
			break;//End switch
		case 1:
			//Spawn second wave
			break;
		}
		++waveNumber; //Increment by 1. Same as:  waveNumber = waveNumber + 1;
		timer = 0f;

		//Optional, randomize wave times.
		spawnTimer = Random.Range(7f, 10f);
	}
}

The other thing that comes to mind is using WaitForSeconds as you mentioned in a Coroutine. Simpler to code, but if you need to adjust things mid run (like triggering a wave early) isn’t as easy as the first way.

    void Start()
	{
		StartCoroutine("Spawner");
	}

	//IEnumerator is the keyword for Coroutines, which can run over multiple game frames.
	//Can be stopped by calling:  StopCoroutine("Spawner");
	IEnumerator Spawner()
	{
		return new WaitForSeconds(7f); //Pauses the coroutine
		//Spawn first wave
		return new WaitForSeconds(7f);
		//Spawn second wave
		//..etc
	}