C# Unity — Random-ish Number (Do-While Loop)

Ryan McCoach
2 min readNov 3, 2023

--

Intro

In article, I will cover a way to use create a quick and easy way to randomize a number, but avoid picking the previous number. This can be helpful when you are OCD and using the Random.Range to choose a game object to appear (power up, enemy, etc.) and hate to see the same thing back-to-back.

This will be utilizing the less popular Do-While loop and this “random” number determines the ring position to fly through.

Current Code

A ring game object is instantiate every couple of seconds using a coroutine. There is an array of positions and rotations that the ring can potentially spawn from.

 _randomNum = Random.Range(0, 4);
GameObject newRing = Instantiate(_ringPrefab, _ringPosArray[_randomNum].transform.position, _ringPosArray[_randomNum].transform.rotation);

Which position/rotation is determined by a variable (_randomNum) that will be assigned a random number from 0–3 using the Random.Range function. Remember the range is exclusive, so the max number is NOT included in the selection.

This method doesn’t prevent the same number being picked consecutively.

Do While vs While Loop

Before getting to the code, it is important to understand the difference these two loops which will explain why one may be better to use compared to the other.

The While Loop will repeatedly run as long as the condition is met,

while (condition)
{
// code to be executed
}

but the condition needs to be met first before entering loop.

The Do-While Loop will execute the code first before checking the condition and

do
{
// your code that you want to execute as a loop
} while (condition);

will repeat until it is met.

The Code

We have two variables (numbers), one for storing the new random number and the other to store the number that was previously selected. First, using the same Random.Range to initialize the previous number.

private int _randomNum;
private int _previousNum = 3;

private void Start()
{
_previousNum = Random.Range(0, 4);
}

Using the Do-While loop we want to first assign the a random number to the new random variable before we check to see if the new random number is the same as the previously selected

 do
{
_randomNum = Random.Range(0, 4);

} while (_randomNum == _previousNum);

_previousNum = _randomNum;

If they are the same, it will loop and picked another random number until it is not equal to the previous number.

Finally, we need to set that newly selected number to the previous number so it is not picked again.

No more repeating rings.

--

--