Invoking a Method that takes variables?


I searched but I couldn’t find, I am trying to Invoke a method that takes variables is this possible and what is the correct way of doing it?

	public virtual void NextWave () {
		wave = waves [thisWave];
		thisEnemy = 0;
		for (int i = 0; i < wave.enemyWave.Count; i++) {
			enemy = wave.enemyWave*;*
  •  	invoke = "Spawn(" + enemy.enemy + ", " + enemy.location + ")";*
  •  	Invoke (invoke, enemy.timer);*
  •  }*
  • }*

  • public void Spawn(GameObject enemyToSpawn, Vector3 spawnLocation) {*

  •  Instantiate (enemyToSpawn, spawnLocation, new Quaternion());*
  • }*
    The code above obviously doesn’t work since you don’t put the () after the method name with Invoke. But it is what I am trying to achieve

You can’t pass arguments to an invoke call, but you can sometimes move those arguments out into the class:

GameObject enemyToSpawn;
Vector3 spawnLocation;

void NextWave() {
    Invoke("Spawn", 5f);

void Spawn() {
    Instantiate(enemyToSpawn, spawnLocation, Quaternion.identity);

If that’s not enough control – and it frequently won’t be – you can look into coroutines:

void NextWave() {
    GameObject enemyToSpawn = ...;
    Vector3 spawnLocation = ...;
    StartCoroutine(Spawn(5f, enemyToSpawn, spawnLocation));

IEnumerator Spawn(float delay, GameObject enemyToSpawn, Vector3 spawnLocation) {
    yield return new WaitForSeconds(delay);
    Instantiate(enemyToSpawn, spawnLocation, Quaternion.identity);

Coroutines are more complicated than Invoke, but they’re quite a bit more powerful to make up for it.