1
\$\begingroup\$

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)?

\$\endgroup\$
6
\$\begingroup\$

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;
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ This is clever and probably the best solution. \$\endgroup\$ – jgallant Jun 17 '16 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 Jun 17 '16 at 11:04
4
\$\begingroup\$

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)];
| improve this answer | |
\$\endgroup\$
  • \$\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 Jun 17 '16 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 Jun 17 '16 at 10:43
  • \$\begingroup\$ Your answer shows otherwise \$\endgroup\$ – user85869 Jun 17 '16 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 Jun 17 '16 at 10:45
2
\$\begingroup\$

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)];
    }
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.