- Home /
Disreguard random number after use...
Using Random.Range, i choose a number at random from 1-10.
But i only want each number to be used once, so if i roll a 3, then re-roll 3 i want it to either roll again, or take 3 out of the list of randomly chooseable (did i just make up a word?) numbers.
Are either of these things possible?
Thanks, Tom :)
Answer by mikebelotti · Aug 14, 2012 at 07:56 PM
Sure. You'll just need to make a random number "pool" of sorts. This can just be a List
or something similar. Fill it with the numbers you want, then do a Random.Range
from 0 to the length of the list. Get the value, remove that index from the list, and repeat until the list is empty.
You could also shuffle the array, and then pick the numbers, one by one. (A search for "shuffle array" will likely give you many different ways to do this.)
Answer by Mander · Aug 14, 2012 at 08:13 PM
sure just store ur last number in a variable
lets say ur first roll is 3 then u store it in a variable
and compare.
if (the new number == to the last number){
re-roll again.
}
Hopefully you don't have an unlucky player who gets stuck in an infinite loop! xD
ahahah that's not possible, unless only 1 value is used xD
Provided you change the if
to a while
(to guarantee a different number is used), it is possible to get stuck in an infinite loop there. In practice, though, it probably won't happen. But, if the range of values is small, the code might get caught in that loop for quite a few cycles, causing a slight frame rate drop.
that is true. so it could be so ezly fixed. maybe u dont reroll if the number is the same just take the number and +1 or + another random. :)
Answer by sman_47o · Aug 14, 2012 at 08:28 PM
the only on or two ways i can think of that are different than those already posted at the moment would be to either the best seems to be:
have an array of already rolled numbers that gets added to every roll and then if a rolled number is equal to any number in that array the code would roll again until it got a number not included in the array. when the array got filled it would be reset.
so for example (sorry this is off the top of my head):
var rolledNumbers : int[]
var rolledNumber : int;
function Start(){
rolledNumbers = new int[10];
}
function onRoll(){
var tempNum : int = Random.Range(1,10);
if( rolledNumbers[tempNum]=tempNum){
return;
}
else{
rolledNumber = tempNum;
rolledNumbers[tempNum] = tempNum;
}
}
}
Your answer
Follow this Question
Related Questions
Excluding values from a Random.range? 1 Answer
Random.Range statement question 1 Answer
Various of Random Numbers? 1 Answer
Picking one of two numbers. 1 Answer
Random Range with limits 2 Answers