📜  random.range unity - C# (1)

📅  最后修改于: 2023-12-03 14:46:55.156000             🧑  作者: Mango

Random.Range in Unity - C#

Random.Range is a method in Unity that generates a random number within a specific range of values. This method can be useful in a variety of situations, such as creating randomized game elements or generating random test data. Let's take a closer look at how to use Random.Range in Unity C#.

Syntax
public static float Range(float minInclusive, float maxExclusive);
public static int Range(int minInclusive, int maxExclusive);
Parameters
  • minInclusive: The minimum value that can be generated, inclusive.
  • maxExclusive: The maximum value that can be generated, exclusive.
Examples

Here are a few examples of how to use Random.Range in Unity C#:

// Generates a random number between -1.0f and 1.0f.
float randomFloat = Random.Range(-1.0f, 1.0f);

// Generates a random number between 0 and 10, inclusive.
int randomInt = Random.Range(0, 11);

// Generates a random number between -100 and 100, inclusive.
int randomInt2 = Random.Range(-100, 101);
Notes
  • When using Random.Range, the minimum value should always be inclusive, while the maximum value should always be exclusive. This means that the minimum value can be generated, but the maximum value cannot.
  • Random number generation can often be tricky when it comes to providing truly random results. Luckily, Unity's implementation of Random is considered to be quite good and should provide suitable randomness for most use-cases.

Overall, Random.Range is a useful tool to have when working with Unity C#. With a few simple parameters, you can generate a random number within a specified range quickly and easily.