- Home /
random range/if conditions?
Hello. How can I use Random.Range(#,#) in combination with an if statement? So I can do something like
(Random.Range(1, 10); if =1 {something} if =2 {something else} if =2 {something else} ...
Thanks
Answer by ina · Dec 26, 2010 at 03:00 AM
Random.Range(a,b)
returns a number between the two endpoint numbers a
(inclusive) and b
, (exclusive). This means, it will return anything between a, a+1, a+2 ... b-2, b-1
To use it, you will want to assign a variable var rand:int=Random.Range(1,10);
, and then, compare it to the various possibilities in your if then. if(rand==1)doSomething(); else if (rand==2)doAnotherThing();
etc.
You may also wish to use if(rand>1)
and comparison operators for entire ranges of numbers.
note - the int version of Random.Range is not inclusive. Random.Range(0, 10) will return a maximum of 9
mea culpa!! and wow - why is the second endpoint for int exclusive? that seems so random
Ranges in languages such as C#, C++, etc. are often represented as [begin, end), with the last element excluded. This is consistent with the use of zero-based indexing, where the index 0 is valid and the index equal to the size of the array is invalid (one past the end). From this point of view, the behavior of the 'int' version of Random.Range() makes sense (for example, it can be used in a straightforward manner to select an element of an array randomly).
Answer by SarperS · Dec 26, 2010 at 04:06 AM
You can also use a switch statement.
var randomNumber:int = Random.Range(0, 2);
switch(randomNumber){
case 0: //Do this, do that break;
case 1: //Do this, do that break;
case 2: //Do this, do that break; }
Your answer
Follow this Question
Related Questions
How to optimize if statements - can't remember term 1 Answer
If statement question... 1 Answer
Random value for if statement 2 Answers
if condition question... 1 Answer
GameObject tag to if condition 1 Answer