- Home /
Performance view over spawn waves method
Regarding Space Shooter tutorial, chapter 13: Spawning Waves.
I changed the suggested code to spawn waves using Update method. Thinking of performance, that could be a worst way to spawn waves of hazard?
public class GameController : MonoBehaviour {
public GameObject hazard;
public Vector3 spawnValues;
private float spawnRate;
private float nextSpawn = 0.0f;
void Update () {
spawnRate = Random.Range (0.5f, 2f);
if (Time.time > nextSpawn) {
nextSpawn = Time.time + spawnRate;
SpawnWave ();
}
}
void SpawnWave () {
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (hazard, spawnPosition, spawnRotation);
}
}
Answer by Bluk · Jul 06, 2015 at 07:22 AM
Short answer: Yes it is a bit worse in terms of performance. But it doesn't change that much to have an extra "if" comparing integers. Random number generation is much slower though, and you run the Random.range() every frame when you only need it periodically.
However, as a rule of thumb, when a task doesnt need to be repeated as often as every frames (which is the Update() frequency), Coroutines are the way to go.
The main reason being that when you execute a function, it runs until completion, whereas in a coroutine, WaitForSeconds() is a non blocking active wait. There are some good simple examples here: http://docs.unity3d.com/Manual/Coroutines.html
Thank you Bluk.
At first, using Update method let the code cleaner, but thinking about the execution of both codes is easy to notice that having a "if" each frame is more expensive than simply run a pause, even using just a "if" comparing integers.
Your answer
Follow this Question
Related Questions
Bouncy platforms/spring jump? 4 Answers
Spawning enemies based on array of times 0 Answers
Spawning two bullets at once! 1 Answer
Freelancer of Freespace type Enemy Ai 2 Answers