If you are using Random.range to generate values, is there any way to exclude some values within the range (for example: pick a number between 1 and 20, but not 6 through 8)?
3 Answers
\$\begingroup\$
\$\endgroup\$
2
Instead of throwing away numbers you don't want, you can pretend you want a number from one slightly smaller range, and then map it into the 2 ranges you want:
float val = Random.Range( 1, 20 - 8 + 6 );
if ( val >= 6 ) val += 2;
-
1\$\begingroup\$ This is clever and probably the best solution. \$\endgroup\$jgallant– jgallant2016-06-17 10:52:03 +00:00Commented Jun 17, 2016 at 10:52
-
1\$\begingroup\$ the problem is that this becomes a code mess when you want to work with multiple excluded ranges and variable ranges. \$\endgroup\$Nzall– Nzall2016-06-17 11:04:23 +00:00Commented Jun 17, 2016 at 11:04
\$\begingroup\$
\$\endgroup\$
4
You could generate a list of values you want to use, and then pick one at random.
Create values:
int[] values = new int[17] { 0,1,2,3,4,5,6,7,10,11,12,13,14,15,16,17,18,19,20 };
Get a random value:
int value = values[Random.Range(0, values.Length)];
-
\$\begingroup\$ What if the OP wants to generate a random number between 10 and 100? You're going to create an array containing those 90 numbers? \$\endgroup\$user85869– user858692016-06-17 10:41:33 +00:00Commented Jun 17, 2016 at 10:41
-
\$\begingroup\$ I probably wouldn`t create an array with the values no, more than likely not depending on the case. \$\endgroup\$jgallant– jgallant2016-06-17 10:43:17 +00:00Commented Jun 17, 2016 at 10:43
-
\$\begingroup\$ Your answer shows otherwise \$\endgroup\$user85869– user858692016-06-17 10:44:32 +00:00Commented Jun 17, 2016 at 10:44
-
1\$\begingroup\$ I am providing a solution to his question, you don`t have to get all upset over this. \$\endgroup\$jgallant– jgallant2016-06-17 10:45:27 +00:00Commented Jun 17, 2016 at 10:45
\$\begingroup\$
\$\endgroup\$
I guess you should go with a solution like this:
int[] validChoices = new int[n]= {1,3,5, whatever until n occurrences};
private int GetRandom(){
return validChoices[Random.Range(0, validChoices.Length)];
}