Описание
Easily generate random data for games.
This static class provides several easy game-oriented ways of generating pseudorandom numbers.
The generator is an Xorshift 128 algorithm, based on the paper Xorshift RNGs by George Marsaglia. It is statically initialized with a high-entropyseed from the operating system, and stored in native memory where it will survive domain reloads. This means that the generator is seeded exactly once on process start, and after that is left entirely under script control.
For more details on the seed, including how to manage it yourself, see InitState. To learn how to save and restore the state of Random, see state.
Versus System.Random
This class has the same name as the .NET Framework class System.Random and serves a similar purpose, but differs in some key ways:
Static vs instanced
UnityEngine.Random
is a static class, and so its state is globally shared. Getting random numbers is easy, because there is no need to new
an instance and manage its storage. However, static state is problematic when working with threads or jobs (the generator will error if used outside the main thread), or if multiple independent random number generators are required. In those cases, managing instances of System.Random
would be a better option.
Float upper bounds are inclusive
All properties and methods in UnityEngine.Random
that work with or derive work from float-based randomness (for example value or ColorHSV) will use an inclusive upper bound. This means that it is possible, though as rare as any other given value, for the max to be randomly returned. In contrast, System.Random.NextDouble()
has an exclusive maximum, and will never return the maximum value, but only a number slightly below it.
Performance
Methods in UnityEngine.Random
have been measured to be between 20% and 40% faster than their equivalents in System.Random
.
Name resolution ambiguity
Because the classes share the name Random
, it can be easy to get a CS0104 "ambiguous reference" compiler error if the System
and UnityEngine
namespaces are both brought in via using
. To disambiguate, either use an alias using Random = UnityEngine.Random;
, fully-qualify the typename e.g. UnityEngine.Random.InitState(123);
, or eliminate the using System
and fully-qualify or alias types from that namespace instead.
Статические Свойства
insideUnitCircle | Возвращает случайную точку внутри или на окружности с радиусом 1,0 (только для чтения). |
insideUnitSphere | Возвращает случайную точку внутри или на сфере с радиусом 1,0 (только для чтения). |
onUnitSphere | Возвращает случайную точку на поверхности сферы с радиусом 1,0 (только для чтения). |
rotation | Возвращает случайное чередование (только для чтения). |
rotationUniform | Возвращает случайное чередование с равномерным распределением (только для чтения). |
state | Получает или задает полное внутреннее состояние генератора случайных чисел. |
value | Возвращает случайное число с плавающей запятой в пределах [0.0..1.0] (включительно) (только для чтения). |
Статические Методы
ColorHSV | Создает случайный цвет из диапазонов HSV и альфа. |
InitState | Инициализирует состояние генератора случайных чисел с помощью начального числа. |
Range | Возвращает случайное число с плавающей запятой в пределах [minInclusive..maxInclusive] (диапазон включительно). |