Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Best practices for timed spawn

Discussion in 'Scripting' started by abenjaminov, Apr 9, 2021.

  1. abenjaminov

    abenjaminov

    Joined:
    Aug 29, 2014
    Posts:
    1
    Im implementing a factory that spawns enemies every X seconds for the entire game and was wondering about best practices for this behaviour.

    I have 2 aproaches in mind and dont really know the benefits of each one of them compared to the other.
    Any Insights on these would be appreciated

    First approach
    Code (CSharp):
    1. public class EnemyFactory {
    2.  
    3.  
    4.     float _timeBetweenSpawns;
    5.     float _timeUntillNextSpawn;
    6.  
    7.     void Awake() {
    8.         _timeUntillNextSpawn = _timeBetweenSpawns;
    9.     }
    10.  
    11.     void Update() {
    12.         _timeUntillNextSpawn -= Time.delaTime;
    13.  
    14.         if(_timeUntillNextSpawn <= 0) {
    15.             _timeUntillNextSpawn = _timeBetweenSpawns;
    16.  
    17.             SpawnEnemy();
    18.         }
    19.     }
    20. }
    Second Approach:

    Code (CSharp):
    1. public class EnemyFactory {
    2.  
    3.     float _timeBetweenSpawns;
    4.     bool _pauseEnemySpawn = false;
    5.  
    6.     void Start() {
    7.        StartCoroutine(SpawnEnemies());
    8.     }
    9.  
    10.     IEnumerator SpawnEnemies() {
    11.         while(!_pauseEnemySpawn) {
    12.             yield return new WaitForSeconds(_timeBetweenSpawns);
    13.             SpawnEnemy();
    14.         }
    15.     }
    16. }


     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    So this is just an Update vs coroutine question, which is a debate as old as time :p

    Just use whatever style you find most maintainable. They are both fine.

    A very minor change when using Update I often do is this:
    Code (CSharp):
    1. public class EnemyFactory {
    2.  
    3.  
    4.     float _timeBetweenSpawns;
    5.     float _timeUntillNextSpawn;
    6.  
    7.     void Awake() {
    8.         _timeUntillNextSpawn = _timeBetweenSpawns;
    9.     }
    10.  
    11.     void Update() {
    12.         _timeUntillNextSpawn -= Time.delaTime;
    13.  
    14.         if(_timeUntillNextSpawn <= 0) {
    15.             _timeUntillNextSpawn += _timeBetweenSpawns;  //I just changed "=" to "+="
    16.  
    17.             SpawnEnemy();
    18.         }
    19.     }
    20. }
    That's just because you'll end up with an average spawn time closer to _timeBetweenSpawns this way. Using "=" will result with an average spawn time ever so slightly longer. Just a very minor thing that you probably would barely notice. Maybe I'm OCD about these kind of things :p