Mubanga
September 10, 2014, 1:33am
1
Hi,
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
1 Answer
1
rutter
September 10, 2014, 2:00am
2
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.
yeah I tried the first one before asking the question but that doesn't really work for me, since the variables change before the delay is over. But I will give a read in to coroutines, thanks!
– MubangaGot everything working, thanks!
– Mubanga