I am trying to generate an integer (Between 1 and 3) that never has the same number in a row, IE never generates consecutive numbers.
I realise this is a fairly basic thing to ask, but I really am having some trouble. My current script, which freezes unity:
#pragma strict
var num : int = 0;
var oldNum : int = 0;
while(num == oldNum)
{
num = Random.Range(1,4);
oldNum = num;
}
function Update()
{
Debug.Log(num);
}
Your loop sets oldnum to num before it goes to the while again, causing a lockup as it never leaves the loop.
Change to this…
Int lastnum = 0;
Do
{
num = random.range(1,4);
} while (num != lastnum);
Lastnum = num;
Soz typed this in on the ipad so make sure yu get the cases correct.
It is freezing because it can never escape from the while loop:
//while still the oldNum keep changing. So lets say oldNum is 2
while(num == oldNum){
num = Random.Range(1,4); //And now this is set to 3
//Yay we are no longer the same as oldNum!... oh wait
oldNum = num; //And here oldNum is changed to num again. So since oldNum and num are the same again we have to loop again... forever
}
Well have you tried typing in a code example on an ipad? Lol. Took me ages to find a squiggly! Oh an your conditions and statements are in light blue, and everyone knows dark blue looks better, and as for green comments… Well nuff said. Oh and calling a variable oldnum is very ageist!
#pragma strict
var num : int = 0;
var oldNum : int = 0;
while(num == oldNum)
{
num = Random.Range(1,4);
}
oldNum = num;
function Update()
{
Debug.Log(num);
}
But this just makes it repeat a number indefinitely… help?
You are calling “Debug.Log” in Update. Update happens every frame, so it would post that message every frame; Execution Order of Event Functions.
You should probably just put this all in a single function so you can call it when needed:
#pragma strict
var num : int = 0;
var oldNum : int = 0;
function NewNum(){
while(num == oldNum){
num = Random.Range(1,4);
}
oldNum = num;
Debug.Log(num);
}
Then just call “NewNum” whenever you want to change num.
@arkon
No actually, but have on a phone so I can relate haha.
var max:int;
var oldNum:int = -1;
// Generate a number between 0 and max - 1
function NewNum():int {
var result = Random.Range(0, max);
if (result == oldNum) result = (result + Random.Range(1, max)) % max;
oldNum = result;
return result;
}