- Home /
 
 
               Question by 
               lefk36 · Mar 21, 2021 at 03:12 PM · 
                airandomstate-machine  
              
 
              how to not repeat the same Random State in a State Machine
I am trying to make my states not repeat twice.
// Function for next State void goToNextState() {
 //  declaration for nextState
 BossState nextState = (BossState)Random.Range(0, (int)BossState.COUNT);
 // goes to next state via string name
 string nextStateString = nextState.ToString() + "State";
 // gets the name of the current state to a string 
 string lastStateString = currentState.ToString() + "State";
 // updates the current state
 if (lastStateString != nextStateString)
 {
     currentState = nextState;
     StartCoroutine(nextStateString);
 }
 
     // stops in case of weird behaviour
     StopCoroutine(lastStateString);
     StartCoroutine(nextStateString);
   
 
               }
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by toficofi · Mar 21, 2021 at 03:38 PM
If you want a state to never repeat, you could keep a list of "used states" and check against that.
 BossState nextState;
 
 if (usedStates.Length == BossState.COUNT) {
     // We have used all the states up! We should abort to avoid getting stuck in an infinite loop.
 }
 
 do {
     nextState = Random.Range(0, (int) BossState.COUNT);
 } while (usedStates.Contains(nextState))
 
 usedStates.Add(nextState);
 
               It would waste less cycles if you instead make a list of "available" states and remove from there once you've picked one, too.
Your answer
 
             Follow this Question
Related Questions
How to exclude int values from Random.Range? 2 Answers
AI pathfinding waypoints 1 Answer
Random Movement Problem 1 Answer