Hi there,
I need to generate a random number in unity that will be different to the last generated random number.
I have the following code and this is how you would do it in something like flash.
function getUniqueRandomSectionNumber(){
var tempSectionNum : int = Random.Range(0, totalSections);
if(tempSectionNum == lastCreatedSectionNum){
getUniqueRandomSectionNumber();
} else {
lastCreatedSectionName = tempSectionNum;
return tempSectionNum;
}
}
However in Unity I don’t seem to be able to run the function from inside itself. In order to try again on the random number.
Hope this makes sense and thanks for any help
Will
TinoCle
November 13, 2016, 10:38pm
4
int rand = Random.Range(0,totalSections);
while(rand==RandyAnterior){
rand = Random.Range(0,totalSections);
}
RandyAnterior = rand;
I know its 2018 but people would still be stumbling upon this question. So, 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. Going through the forum i came across a code and modified it and then 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. Hope this helps. Cheers.
You could have the code in a while loop that only ends when the last random number is not equal to the current one. e.g:
function getUniqueRandomSectionNumber(){
var hasFoundUniqueRandomSelection : bool;
var tempSectionNum : int;
while (!hasFoundUniqueRandomSelection) {
tempSectionNum = Random.Range(0, totalSections);
if(tempSectionNum != lastCreatedSectionNum){
hasFoundUniqueRandomSelection = true;
lastCreatedSectionName = tempSectionNum;
}
}
return tempSectionNum;
}
Apologies if I’ve made any mistakes, not accustomed to working with javascript.
Sir/Ma’am, even I had the same problem before but I fixed it with an if-condition.
currentNumber = Random.Range (0, markers.Length);
if (lastNumber != currentNumber)
{
lastNumber = currentNumber;
} else
{
currentNumber = Random.Range (0, markers.Length);
lastNumber = currentNumber;
}