Search code examples
visual-studiounity-game-enginecountinstantiation

Instantiation does not stop at count and adds one extra. Solution?


So, this is my code. There's instantiate code within SpawnObj1() & SpawnObj2(). The prefabs inside SpawnObj()(1 & 2) spawns properly but SpawnObj1 spawns one extra prefab when the count is at 5. How do I stop instantiation exactly at that count?

 public void Spawner()
     {
         if (objCount < 5)
         {
             SpawnObj1();
         }
 
         if (objCount >= 5)
         {
             SpawnObj2();
         }
     }

BTW, objCount is objCount ++ within SpawnObj().


Solution

  • I guess you increment "objCount" in SpanwObject1() and in SpawnObject2(). If we follow the code when objCount is 4

    objCount is 4
    SpawnObject1() // increment the objCount
    objCount is 5
    
    So the condition objCount >= 5 is valid here in the same call of "Spawner()"
    SpawnObject2()
    

    An easy fix is to modify your code like this :

    public void Spawner()
     {
         if (objCount < 5)
         {
             SpawnObject1();
         }
         else if (objCount >= 5)
         {
             SpawnObject2();
         }
     }
    

    with this fix, the SpawnObject2() won't be called just after SpawnObject1 when objCount is 4. You can also add a return after each "SpawnObject..."