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

Resolved Any way to optimize this?

Discussion in 'Scripting' started by jlorenzi, Aug 8, 2022.

  1. jlorenzi

    jlorenzi

    Joined:
    May 2, 2021
    Posts:
    290
    So I'm making an arcade style wave based fighting game. Every 5 waves a boss spawns, the way I know which boss to spawn is by having a variable for the index of the next boss I want to spawn in a list, and after I spawn a boss I add 1 to that variable so next time the wave is a multiple of 5 it'll already be at the next index in the list of bosses.

    The problem is that I want the player to be able to skip to waves they've already beaten before, which messes up the system because if they skip past the first boss, it'll still spawn the first boss on the next boss wave because the variable for the boss index is still at 0.

    The way I'm avoiding this is by checking if the wave is at a certain number.
    Code (CSharp):
    1.     private void Start()
    2.     {
    3.         wave = ES3.Load<int>("Spawn Wave");
    4.  
    5.         if ( wave == 10 )
    6.         {
    7.             nextBoss = 1;
    8.         }
    9.     }
    Which works and isn't that bad when you only have 2 bosses in the game, but when I add more bosses, say 10 of them it'll start to become spaghetti code.

    So how would I optimize this?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Compute the boss as a function of the wave:

    nextBoss = wave / 5;


    Might need +1 or -1 depending on how you've designed your numbering system, either zero- or one-based.

    And then isBossLevel becomes a modulo function of that same system:

    bool isBossLevel = (wave % 5) == 4;
     
    jlorenzi and Munchy2007 like this.