Duplicated if condition

Hello,

following the video, there is a point where they are using recursion, I just thought instead of using a second if, that I understand it’s the same as the previous one, use just one if condition, I would do it like this:

void spawnUntilFull(){        
      Transform freePosition = nextFreePosition();        
      if(freePosition){            
         GameObject enemy = Instantiate(enemyPrefab, freePosition.position, Quaternion.identity) as GameObject;            
         enemy.transform.parent = freePosition;            
         Invoke("spawnUntilFull", spawnDelay);        
      }       
      /*if(nextFreePosition()){            
          Invoke("spawnUntilFull", spawnDelay);        
      }*/    
}

Tell me please if maybe I’m missing something.
Sorry to put the code directly, I tried to use pastebin, but when putting the link and creating the topic, I was getting a message telling that new users can’t put more than 2 links in the posts, but I was puting just one…

Best regards,
Jordi

1 Like

I had the same thought, definitely looks like it’d be better the way you’ve written it here.

The way it’s implemented in the video:

void SpawnUntilFull() {
  Transform freePosition = NextFreePosition();
  if (freePosition) {
    GameObject enemy = Instantiate (enemyPrefab, freePosition.transform.position, Quaternion.identity) as GameObject;
    enemy.transform.parent = freePosition;
  }
  if (NextFreePosition()) {
    Invoke ("SpawnUntilFull", spawnDelay);
  {
}

NextFreePosition() is called to determine if SpawnUntilFull() should be called - but the first thing called in SpawnUntilFull() is NextFreePosition().

So far as I can tell, there’s no reason to call it that second time at the end of the execution - even for timing issues, it seems like the only thing that would be relevant would be the call at the start of the invocation.

As written, it looks like NextFreePosition() would be called one more time than necessary on every invocation of SpawnUntilFull()

I agree that this version seems more efficient.

I had it that way first, but then I tried it the way it was in the video, and as expected it behaves exactly the same way. So I switched it back, because I feel our way is, as Mochnant says, more efficient.

This lecture has confused me quite a bit. However from my own observed experience. Changing the code as suggested and destroying all enemies in the formation seems to make them respawn instantly instead of when the whole formation is destroyed.