I have 4 colors. I want to make it so that the player can\'t be the same color 2 times in a row. When a player collides with an object, the RandomColor()
is called.
What you need to do is add a judgement if the RandomColor returns a same color as prev one, just call it again, easy right?
First, you need a function that can generate a random number with exclusion. Below is what I use for that:
int RandomWithExclusion(int min, int max, int exclusion)
{
int result = UnityEngine.Random.Range(min, max - 1);
return (result < exclusion) ? result : result + 1;
}
Each time you call it, you need to store the result in a global variable so that you will pass that to the exclusion
parameter next time you call it again.
I modified the function so that you don't have to do that each time it is called. The new RandomWithExclusion
function will do that for you.
int excludeLastRandNum;
bool firstRun = true;
int RandomWithExclusion(int min, int max)
{
int result;
//Don't exclude if this is first run.
if (firstRun)
{
//Generate normal random number
result = UnityEngine.Random.Range(min, max);
excludeLastRandNum = result;
firstRun = false;
return result;
}
//Not first run, exclude last random number with -1 on the max
result = UnityEngine.Random.Range(min, max - 1);
//Apply +1 to the result to cancel out that -1 depending on the if statement
result = (result < excludeLastRandNum) ? result : result + 1;
excludeLastRandNum = result;
return result;
}
Test:
void Update()
{
Debug.Log(RandomWithExclusion(0, 4));
}
The last number will never appear in the next function call.
For your specific solution, simply replace
int index = Random.Range(0, 4);
with
int index = RandomWithExclusion(0, 4);