# How to generate a random number which is different from the last

As the title suggests, what I want is, how to generate a random number which is not equal to the previously generated number. For example, if Unity generates a number say 5, then the next number shouldn’t be 5 but something else say 6 but the number after 6 can be 5 so I didn’t use Lists. Is there an efficient method to do this? I know there are some resources on the Internet but they didn’t give proper answers.
Thank you and any help will be appreciated.

private int lastNumber;

``````int GetRandom (int min, int max)
{
int rand = Random.Range (min, max);
while (rand == lastNumber)
rand = Random.Range (min, max);
lastNumber = rand;
return rand;
}
``````

Something like that should do it, just call this function where you would normally call Random.Range.

prevNum = newNum;

``````newNum = Random.value * range;
if (newNum == prevNum)
newNum = Random.value * range;

//use newNum here
``````

Maybe this would be helpful for someone. I was trying to spawn enemy planes in Augmented Reality. I wanted them to be randomly spawned but at a distance. For example, if one plane is spawned at 0,0,0. I wanted the next plane to be spawned at 0+20 or 0-20 on the X-Axis. Like, the new plane should spawn at 20 or more points from the present spawned point in positive and negative direction. Using @Namey5 solution, i came to this:

``````    void RandonDistanceAxis()
{
distanceX = Random.Range (-70, 70);
while (distanceX <= tempx + 20 && distanceX >= tempx - 20 )
{
distanceX = Random.Range (-70, 70);
}
tempx = distanceX;

distanceY = Random.Range (-10,10);
distanceZ = Random.Range (60,90);
}
``````

While declaring the tempx variable, give it a value of something out of the Range. I used 71. And it worked perfectly fine.