Unity Random.Range() - Unity Random Number Generation
Unity Random Number Generation
Friends, in this post I will show you how to generate a random number between 2 values entered with Unity.In Unity, to generate a random number we use Random.Range(min, max) and enter the min and max range we want, allowing this code to generate a random number.
Here, there is an important point when entering the min max range and you need to pay attention to this: while the value you enter for min is included, the max value is not fully included, let me explain it like this.
When we say Random.Range(1,10) it produces numbers in the value of 1,2,3,4,5,6,7,8,9 but not 10. If we want it to include the number 10 as well, we need to use Random.Range(1,10+1) or Random.Range(1,11).
I usually prefer to add it as 10+1 when using it, because indicating how many max I want to generate by adding +1 makes the code more clear.
Unity Generate Random INT Number
void Start(){
int randomNum;
randomNum = Random.Range(1,10+1); // Generates an int number between 1 and 10 inclusive.
}
Unity Generate Random Float Number
void Start(){
float randomNum;
randomNum = Random.Range(1f,(10+1)f); // Generates an int number between 1 and 10 inclusive, but the generated numbers are fractional like 1.13, 2.49, 9.54, etc.
}


Yorum Gönder