Class RandomUtil
Provides deterministic and non-deterministic random utilities for Unity and general C# usage. Serves as the main facade for random number generation in Scylla, offering factory methods for all supported RNG algorithms and a comprehensive suite of utility methods that operate uniformly over any IRandomSource implementation.
Inherited Members
Namespace: Scylla.Core.Util.Random
Assembly: ScyllaCore.dll
Syntax
public static class RandomUtil
Remarks
Use the factory methods in this class to obtain an IRandomSource and then pass it to the static utility helpers (or use the extension methods in RandomExtensions) to generate booleans, integers, floats, Unity types, or perform operations such as shuffling and weighted selection.
For deterministic gameplay, the recommended workflow is:
- Create an RNG with a fixed seed via CreateXoshiro256(ulong) or CreateDeterministic(int).
- Advance the generator using the static helper methods or RandomExtensions extension methods on the returned instance.
- Snapshot and restore state using the algorithm-specific
GetState/SetStatemethods when save-game determinism is required.
Available RNG algorithms (use RandomAlgorithm for generic selection):
- Xoshiro256StarStar - Default, fast, excellent statistical quality, 256-bit state. Best choice for most gameplay and procedural generation.
- Xoroshiro128Plus - Lightweight 128-bit state alternative. Ideal when many independent streams are needed or memory is constrained.
- PCG32 - Permuted Congruential Generator with native multi-stream support. Excellent quality in a compact, serializable state.
- SplitMix64RNG - Minimal 64-bit state. Best for seeding other generators or hash-like one-off randomness.
- MersenneTwister - MT19937 with a very long period (~2.5 KB state). Best suited for offline tooling and scientific simulations.
For security-sensitive randomness (tokens, keys, nonces) use CreateCrypto() or the static helpers CryptoFillBytes(byte[], int, int) and CryptoNextInt(int, int). Crypto sources are non-deterministic and slower than the gameplay algorithms.
Methods
Create(RandomAlgorithm, string)
Creates an IRandomSource of the algorithm specified by
algorithm, initialized with a stable hash of the given string seed.
This overload is useful when the algorithm is chosen at runtime and the seed comes
from a human-readable value such as a level name or world identifier.
Declaration
public static IRandomSource Create(RandomAlgorithm algorithm, string seed)
Parameters
| Type | Name | Description |
|---|---|---|
| RandomAlgorithm | algorithm | The RandomAlgorithm to instantiate. See RandomAlgorithm for descriptions of each option. |
| string | seed | The string whose hash is used as the seed. Must not be |
Returns
| Type | Description |
|---|---|
| IRandomSource | A new IRandomSource whose concrete type corresponds to
|
Exceptions
| Type | Condition |
|---|---|
| ArgumentOutOfRangeException | Thrown if |
Create(RandomAlgorithm, ulong)
Creates an IRandomSource of the algorithm specified by
algorithm, initialized with the given 64-bit seed.
This overload is useful when the algorithm is chosen at runtime (e.g., from a
configuration asset or user setting) without needing algorithm-specific factory calls.
Declaration
public static IRandomSource Create(RandomAlgorithm algorithm, ulong seed)
Parameters
| Type | Name | Description |
|---|---|---|
| RandomAlgorithm | algorithm | The RandomAlgorithm to instantiate. Each value maps to a specific algorithm implementation with different performance and state characteristics. See RandomAlgorithm for descriptions of each option. |
| ulong | seed | The 64-bit seed that fully determines the generated sequence. Identical algorithm and seed values always produce identical sequences. |
Returns
| Type | Description |
|---|---|
| IRandomSource | A new IRandomSource whose concrete type corresponds to
|
Exceptions
| Type | Condition |
|---|---|
| ArgumentOutOfRangeException | Thrown if |
CreateCrypto()
Creates and returns a CryptoRandomSource backed by RandomNumberGenerator. Suitable for security-sensitive values such as session tokens, encryption keys, or nonces.
Declaration
public static CryptoRandomSource CreateCrypto()
Returns
| Type | Description |
|---|---|
| CryptoRandomSource | A new CryptoRandomSource instance. The caller is responsible for disposing the returned instance when it is no longer needed. |
Remarks
Cryptographic RNG is non-deterministic and significantly slower than the gameplay algorithms. Do not use it in hot paths or per-frame code.
For a fire-and-forget approach that handles disposal automatically, use CryptoFillBytes(byte[], int, int) or CryptoNextInt(int, int).
See Also
CreateDeterministic(int)
Creates a backwards-compatible RandomUtil.DeterministicRNG seeded with a 32-bit signed integer. The underlying algorithm is xoshiro256** expanded from the seed via SplitMix64.
Declaration
public static RandomUtil.DeterministicRNG CreateDeterministic(int seed)
Parameters
| Type | Name | Description |
|---|---|---|
| int | seed | The seed value that fully determines the generated sequence. Identical seeds always produce identical sequences across runs and platforms. |
Returns
| Type | Description |
|---|---|
| RandomUtil.DeterministicRNG | A RandomUtil.DeterministicRNG initialized with |
Remarks
This method is provided for backwards compatibility. New code should prefer CreateXoshiro256(ulong) or Create(RandomAlgorithm, ulong).
CreateDeterministic(string)
Creates a backwards-compatible RandomUtil.DeterministicRNG seeded with a stable hash of the given string. The same string always produces the same sequence.
Declaration
public static RandomUtil.DeterministicRNG CreateDeterministic(string seed)
Parameters
| Type | Name | Description |
|---|---|---|
| string | seed | The string whose hash is used as the seed. Must not be |
Returns
| Type | Description |
|---|---|
| RandomUtil.DeterministicRNG | A RandomUtil.DeterministicRNG initialized from a hash of |
Remarks
This method is provided for backwards compatibility. New code should prefer CreateXoshiro256(string) or Create(RandomAlgorithm, string).
CreateDeterministic(ulong)
Creates a backwards-compatible RandomUtil.DeterministicRNG seeded with a 64-bit unsigned integer. The underlying algorithm is xoshiro256** expanded from the seed via SplitMix64.
Declaration
public static RandomUtil.DeterministicRNG CreateDeterministic(ulong seed)
Parameters
| Type | Name | Description |
|---|---|---|
| ulong | seed | The seed value that fully determines the generated sequence. Identical seeds always produce identical sequences across runs and platforms. |
Returns
| Type | Description |
|---|---|
| RandomUtil.DeterministicRNG | A RandomUtil.DeterministicRNG initialized with |
Remarks
This method is provided for backwards compatibility. New code should prefer CreateXoshiro256(ulong) or Create(RandomAlgorithm, ulong).
CreateMersenneTwister(string)
Creates a MersenneTwister (MT19937) RNG seeded with a stable hash of the given string. The same string always produces the same sequence.
Declaration
public static MersenneTwister CreateMersenneTwister(string seed)
Parameters
| Type | Name | Description |
|---|---|---|
| string | seed | The string whose hash is used to initialize the 624-element MT state. Must not be |
Returns
| Type | Description |
|---|---|
| MersenneTwister | A new MersenneTwister instance seeded from the hash of |
CreateMersenneTwister(ulong)
Creates a MersenneTwister (MT19937) RNG seeded with the given 64-bit value. The Mersenne Twister has a very long period of 2^19937 − 1 and approximately 2.5 KB of state, making it suitable for offline tools, scientific simulations, or any context where period length is critical and performance is not.
Declaration
public static MersenneTwister CreateMersenneTwister(ulong seed)
Parameters
| Type | Name | Description |
|---|---|---|
| ulong | seed | The 64-bit seed used to initialize the 624-element internal state array. Identical seeds always produce identical sequences. |
Returns
| Type | Description |
|---|---|
| MersenneTwister | A new MersenneTwister instance initialized from |
Remarks
For real-time gameplay use CreateXoshiro256(ulong) instead. The Mersenne Twister's large state makes it costly to initialize and unsuitable for many short-lived per-frame instances.
CreatePCG32(string, ulong)
Creates a PCG32 RNG seeded with a stable hash of the given string and an optional stream identifier.
Declaration
public static PCG32 CreatePCG32(string seed, ulong stream = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| string | seed | The string whose hash is used as the seed. Must not be |
| ulong | stream | The stream identifier that selects an independent output sequence for this seed.
Defaults to |
Returns
| Type | Description |
|---|---|
| PCG32 | A new PCG32 instance seeded from the hash of |
CreatePCG32(ulong, ulong)
Creates a PCG32 RNG seeded with the given 64-bit value and an optional stream identifier. PCG32 (Permuted Congruential Generator) produces excellent statistical output in a very compact state and natively supports multiple independent streams from a single seed.
Declaration
public static PCG32 CreatePCG32(ulong seed, ulong stream = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| ulong | seed | The 64-bit seed that determines the base sequence. Identical seeds with the same stream always produce identical output. |
| ulong | stream | The stream identifier, which selects one of many independent output sequences for
this seed. Different stream values produce statistically independent sequences.
Defaults to |
Returns
| Type | Description |
|---|---|
| PCG32 | A new PCG32 instance initialized from |
CreateSplitMix64(string)
Creates a SplitMix64RNG seeded with a stable hash of the given string. The same string always produces the same sequence.
Declaration
public static SplitMix64RNG CreateSplitMix64(string seed)
Parameters
| Type | Name | Description |
|---|---|---|
| string | seed | The string whose hash is used as the seed. Must not be |
Returns
| Type | Description |
|---|---|
| SplitMix64RNG | A new SplitMix64RNG instance seeded from the hash of |
CreateSplitMix64(ulong)
Creates a SplitMix64RNG seeded with the given 64-bit value. SplitMix64 has minimal state (one 64-bit integer) and is extremely fast, making it the best choice for one-shot hash-like random values or for seeding other generators.
Declaration
public static SplitMix64RNG CreateSplitMix64(ulong seed)
Parameters
| Type | Name | Description |
|---|---|---|
| ulong | seed | The initial 64-bit state. Identical seeds always produce identical sequences.
Avoid a seed of |
Returns
| Type | Description |
|---|---|
| SplitMix64RNG | A new SplitMix64RNG instance initialized from |
CreateXoroshiro128(string)
Creates a Xoroshiro128Plus RNG seeded with a stable hash of the given string. The same string always produces the same sequence.
Declaration
public static Xoroshiro128Plus CreateXoroshiro128(string seed)
Parameters
| Type | Name | Description |
|---|---|---|
| string | seed | The string whose hash is used as the seed. Must not be |
Returns
| Type | Description |
|---|---|
| Xoroshiro128Plus | A new Xoroshiro128Plus instance seeded from the hash of |
CreateXoroshiro128(ulong)
Creates a Xoroshiro128Plus RNG seeded with the given 64-bit value. This algorithm has a compact 128-bit state, making it ideal when many independent RNG instances are needed simultaneously or when per-entity memory is constrained.
Declaration
public static Xoroshiro128Plus CreateXoroshiro128(ulong seed)
Parameters
| Type | Name | Description |
|---|---|---|
| ulong | seed | The 64-bit seed that fully determines the generated sequence. The seed is expanded to the 128-bit state using SplitMix64. Identical seeds always produce identical sequences. |
Returns
| Type | Description |
|---|---|
| Xoroshiro128Plus | A new Xoroshiro128Plus instance initialized from |
CreateXoshiro256(string)
Creates a Xoshiro256StarStar RNG seeded with a stable hash of the given string. The same string always produces the same sequence.
Declaration
public static Xoshiro256StarStar CreateXoshiro256(string seed)
Parameters
| Type | Name | Description |
|---|---|---|
| string | seed | The string whose hash is used as the seed. Must not be |
Returns
| Type | Description |
|---|---|
| Xoshiro256StarStar | A new Xoshiro256StarStar instance seeded from the hash of |
CreateXoshiro256(ulong)
Creates a Xoshiro256StarStar RNG seeded with the given 64-bit value. This is the default and recommended algorithm for most gameplay and procedural generation scenarios: it is fast, produces excellent statistical output, and has a 256-bit state that is sufficient for virtually all game uses.
Declaration
public static Xoshiro256StarStar CreateXoshiro256(ulong seed)
Parameters
| Type | Name | Description |
|---|---|---|
| ulong | seed | The 64-bit seed that fully determines the generated sequence. The seed is expanded to the 256-bit state using SplitMix64. Identical seeds always produce identical sequences. |
Returns
| Type | Description |
|---|---|
| Xoshiro256StarStar | A new Xoshiro256StarStar instance initialized from |
CryptoFillBytes(byte[], int, int)
Fills a segment of buffer with cryptographically secure random bytes
using a disposable CryptoRandomSource that is created and disposed
internally. Suitable for one-shot security-sensitive fills without manually managing
the crypto source lifetime.
Declaration
public static void CryptoFillBytes(byte[] buffer, int offset = 0, int count = -1)
Parameters
| Type | Name | Description |
|---|---|---|
| byte[] | buffer | The byte array to fill. Must not be |
| int | offset | The zero-based index in |
| int | count | The number of bytes to write. Pass |
Remarks
Each call to this method constructs and disposes a new CryptoRandomSource. For repeated fills in a loop, prefer creating a single source via CreateCrypto() and disposing it when done.
See Also
CryptoNextInt(int, int)
Returns a cryptographically secure random int in the range
[minInclusive, maxExclusive).
A new CryptoRandomSource is created and disposed for each call.
Declaration
public static int CryptoNextInt(int minInclusive, int maxExclusive)
Parameters
| Type | Name | Description |
|---|---|---|
| int | minInclusive | The inclusive lower bound of the random value range. May be negative. |
| int | maxExclusive | The exclusive upper bound. Must be strictly greater than |
Returns
| Type | Description |
|---|---|
| int | A cryptographically secure random |
Remarks
Each call constructs and disposes a new CryptoRandomSource. For repeated calls in a loop, create a single source via CreateCrypto() and dispose it when done.
Exceptions
| Type | Condition |
|---|---|
| ArgumentException | Thrown if |
FromSystemRandom(Random)
Wraps an existing Random instance as an IRandomSource, allowing it to be used with all RandomUtil helper and extension methods.
Declaration
public static IRandomSource FromSystemRandom(Random random)
Parameters
| Type | Name | Description |
|---|---|---|
| Random | random | The Random instance to wrap. Must not be |
Returns
| Type | Description |
|---|---|
| IRandomSource | A new IRandomSource that delegates to |
Remarks
This adapter is useful for integrating legacy code that already manages a Random with the Scylla random API.
FromUnityRandom()
Returns an IRandomSource backed by UnityEngine.Random, allowing Unity's built-in RNG to participate in RandomUtil helpers and extension methods.
Declaration
public static IRandomSource FromUnityRandom()
Returns
| Type | Description |
|---|---|
| IRandomSource | A new UnityRandomSource instance. All calls advance the global
|
Remarks
UnityEngine.Random is not thread-safe and maintains global state.
Only use this source from the main Unity thread.
For deterministic gameplay use CreateXoshiro256(ulong) instead, which gives full control over seeding and state.
GetUnityRandomState()
Returns a snapshot of the current global UnityEngine.Random state.
The snapshot can be stored and later passed to SetUnityRandomState(State)
to restore the Unity RNG to this exact position in its sequence.
Declaration
public static Random.State GetUnityRandomState()
Returns
| Type | Description |
|---|---|
| Random.State | A |
InsideUnitCircle(IRandomSource)
Returns a point uniformly distributed inside the unit circle (radius < 1). Uses rejection sampling in a [-1, 1] × [-1, 1] square to avoid distortion. The returned vector has length in the range [0, 1).
Declaration
public static Vector2 InsideUnitCircle(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate candidate coordinates. Must not be |
Returns
| Type | Description |
|---|---|
| Vector2 | A UnityEngine.Vector2 whose components are in [-1, 1] and whose magnitude
is strictly less than |
Remarks
For a point uniformly distributed on the unit circle boundary (not interior) use OnUnitCircle(IRandomSource) instead.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
InsideUnitSphere(IRandomSource)
Returns a point uniformly distributed inside the unit sphere (radius < 1).
Uses rejection sampling in a [-1, 1]³ cube. The returned vector has magnitude
strictly less than 1.
Declaration
public static Vector3 InsideUnitSphere(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate candidate coordinates. Must not be |
Returns
| Type | Description |
|---|---|
| Vector3 | A UnityEngine.Vector3 whose magnitude is strictly less than |
Remarks
For a direction vector on the sphere surface use OnUnitSphere(IRandomSource) instead.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
NextBool(IRandomSource, float)
Returns a random boolean value, where the probability of true is controlled
by pTrue. At the default of 0.5 the result is a fair coin flip.
Declaration
public static bool NextBool(IRandomSource rng, float pTrue = 0.5)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying uniform float. Must not be |
| float | pTrue | The probability of the method returning |
Returns
| Type | Description |
|---|---|
| bool |
|
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentOutOfRangeException | Thrown if |
NextDouble(IRandomSource, double, double)
Returns a uniformly distributed random double in the closed range
[min, max].
If min and max are approximately equal
(within double epsilon), min is returned directly.
Declaration
public static double NextDouble(IRandomSource rng, double min, double max)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying uniform [0, 1) value.
Must not be |
| double | min | The inclusive lower bound of the range. May be negative. |
| double | max | The inclusive upper bound of the range. Must be greater than or equal to
|
Returns
| Type | Description |
|---|---|
| double | A |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
NextDouble01(IRandomSource)
Returns a uniformly distributed double in the half-open range [0, 1).
Derived from 53 random bits mapped to the double mantissa, giving the maximum
achievable precision for a uniform [0, 1) double.
Declaration
public static double NextDouble01(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying 64-bit value. Must not be |
Returns
| Type | Description |
|---|---|
| double | A |
Remarks
This is the double counterpart to NextFloat01(IRandomSource) and is used internally by NextDouble(IRandomSource, double, double).
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
NextFloat(IRandomSource, float, float)
Returns a uniformly distributed random float in the closed range
[min, max].
If min and max are approximately equal
(within float epsilon), min is returned directly.
Declaration
public static float NextFloat(IRandomSource rng, float min, float max)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying uniform [0, 1) value.
Must not be |
| float | min | The inclusive lower bound of the range. May be negative or larger than
|
| float | max | The inclusive upper bound of the range. Must be greater than or equal to
|
Returns
| Type | Description |
|---|---|
| float | A |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
NextFloat01(IRandomSource)
Returns a uniformly distributed float in the half-open range [0, 1).
Derived from 24 random bits mapped to the float mantissa, giving the highest
representable precision for a uniform [0, 1) float.
Declaration
public static float NextFloat01(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying 32-bit value. Must not be |
Returns
| Type | Description |
|---|---|
| float | A |
Remarks
This is the lowest-level float primitive used internally by NextFloat(IRandomSource, float, float) and the extension method NextFloat(IRandomSource). Prefer those methods for ranged values; call this only when a raw [0, 1) float is needed.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
NextIndex(IRandomSource, int)
Returns a uniformly distributed random index in the range [0, count).
Equivalent to NextInt(rng, 0, count) but communicates intent when selecting
an element from a collection by index.
Declaration
public static int NextIndex(IRandomSource rng, int count)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the index. Must not be |
| int | count | The exclusive upper bound, typically the number of elements in a collection.
Must be greater than |
Returns
| Type | Description |
|---|---|
| int | A random |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentOutOfRangeException | Thrown if |
NextInt(IRandomSource, int, int)
Returns a uniformly distributed random int in the range
[minInclusive, maxExclusive).
Uses rejection sampling internally to eliminate modulo bias.
Declaration
public static int NextInt(IRandomSource rng, int minInclusive, int maxExclusive)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying raw bits. Must not be |
| int | minInclusive | The inclusive lower bound of the random value to generate. May be negative. |
| int | maxExclusive | The exclusive upper bound. Must be strictly greater than |
Returns
| Type | Description |
|---|---|
| int | A random |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
NextLong(IRandomSource, long, long)
Returns a uniformly distributed random long in the range
[minInclusive, maxExclusive).
Uses rejection sampling internally to eliminate modulo bias.
Declaration
public static long NextLong(IRandomSource rng, long minInclusive, long maxExclusive)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying 64-bit raw bits. Must not be |
| long | minInclusive | The inclusive lower bound of the random value to generate. May be negative. |
| long | maxExclusive | The exclusive upper bound. Must be strictly greater than |
Returns
| Type | Description |
|---|---|
| long | A random |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
NextSign(IRandomSource)
Returns +1 or -1 with equal probability. Useful for randomly flipping
a direction, sign, or side in gameplay logic.
Declaration
public static int NextSign(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the random bit. Must not be |
Returns
| Type | Description |
|---|---|
| int |
|
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
NextUInt(IRandomSource, uint, uint)
Returns a uniformly distributed random uint in the range
[minInclusive, maxExclusive).
Declaration
public static uint NextUInt(IRandomSource rng, uint minInclusive, uint maxExclusive)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying 32-bit raw bits. Must not be |
| uint | minInclusive | The inclusive lower bound of the random value to generate. |
| uint | maxExclusive | The exclusive upper bound. Must be strictly greater than |
Returns
| Type | Description |
|---|---|
| uint | A random |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
NextULong(IRandomSource, ulong, ulong)
Returns a uniformly distributed random ulong in the range
[minInclusive, maxExclusive).
Declaration
public static ulong NextULong(IRandomSource rng, ulong minInclusive, ulong maxExclusive)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the underlying 64-bit raw bits. Must not be |
| ulong | minInclusive | The inclusive lower bound of the random value to generate. |
| ulong | maxExclusive | The exclusive upper bound. Must be strictly greater than |
Returns
| Type | Description |
|---|---|
| ulong | A random |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
OnUnitCircle(IRandomSource)
Returns a point uniformly distributed on the perimeter of the unit circle (radius == 1).
Equivalent to a normalized 2D direction vector. The angle is sampled uniformly in
[0, 2π) and the result always has magnitude exactly 1.
Declaration
public static Vector2 OnUnitCircle(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the angle. Must not be |
Returns
| Type | Description |
|---|---|
| Vector2 | A UnityEngine.Vector2 lying on the unit circle with magnitude |
Remarks
For a point uniformly distributed inside the circle (not on the boundary) use InsideUnitCircle(IRandomSource) instead.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
OnUnitSphere(IRandomSource)
Returns a direction uniformly distributed on the surface of the unit sphere (radius == 1).
Uses the Marsaglia (1972) rejection method to guarantee true spherical uniformity.
The returned vector always has magnitude exactly 1.
Declaration
public static Vector3 OnUnitSphere(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate candidate coordinates. Must not be |
Returns
| Type | Description |
|---|---|
| Vector3 | A UnityEngine.Vector3 lying on the unit sphere with magnitude |
Remarks
This method uses rejection sampling and loops until a valid point is found, so the number of iterations is not fixed (expected value is approximately 1.27 iterations). For a point inside the sphere use InsideUnitSphere(IRandomSource) instead.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
PickOne<T>(IRandomSource, IReadOnlyList<T>)
Selects and returns a single uniformly random element from the provided list. Each element has an equal probability of being selected.
Declaration
public static T PickOne<T>(IRandomSource rng, IReadOnlyList<T> list)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the selection index. Must not be |
| IReadOnlyList<T> | list | The list to pick from. Must not be |
Returns
| Type | Description |
|---|---|
| T | A randomly selected element from |
Type Parameters
| Name | Description |
|---|---|
| T | The type of elements contained in the list. |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
See Also
PickWeightedIndex(IRandomSource, IReadOnlyList<float>)
Selects a random index from the given weight list using linear scan weighted sampling.
An index is chosen with probability proportional to its weight: an element with weight
2 is twice as likely to be selected as an element with weight 1.
Declaration
public static int PickWeightedIndex(IRandomSource rng, IReadOnlyList<float> weights)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to draw a uniform value in [0, totalWeight). Must not be |
| IReadOnlyList<float> | weights | A list of non-negative weight values. All weights must be >= 0 and the total sum
must be > 0. Must not be |
Returns
| Type | Description |
|---|---|
| int | The zero-based index of the selected item. The probability of index |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
| ArgumentOutOfRangeException | Thrown if any weight in |
See Also
PickWeighted<T>(IRandomSource, IReadOnlyList<T>, IReadOnlyList<float>)
Selects and returns a random element from items using proportional
weighted sampling. The element at index i is selected with probability
weights[i] / sum(weights).
Declaration
public static T PickWeighted<T>(IRandomSource rng, IReadOnlyList<T> items, IReadOnlyList<float> weights)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used for sampling. Must not be |
| IReadOnlyList<T> | items | The list of items to select from. Must not be |
| IReadOnlyList<float> | weights | A list of non-negative weight values, one per element in |
Returns
| Type | Description |
|---|---|
| T | The element from |
Type Parameters
| Name | Description |
|---|---|
| T | The type of elements in the item list. |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
| ArgumentException | Thrown if |
See Also
RotationUniform(IRandomSource)
Returns a UnityEngine.Quaternion sampled uniformly at random from the group of all 3D rotations (SO(3)). Uses the Shoemake (1992) method, which samples three uniform values and constructs a unit quaternion in a way that avoids clustering at the poles.
Declaration
public static Quaternion RotationUniform(IRandomSource rng)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate three independent uniform [0, 1) values.
Must not be |
Returns
| Type | Description |
|---|---|
| Quaternion | A unit UnityEngine.Quaternion representing a uniformly distributed random rotation. The returned quaternion is guaranteed to be normalized. |
Remarks
Unlike a naive approach that samples Euler angles uniformly, this method produces a truly uniform distribution over orientation space with no angular bias.
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
SetUnityRandomState(State)
Restores the global UnityEngine.Random state to a previously captured snapshot,
causing subsequent Unity random calls to reproduce the same sequence that followed
the original snapshot.
Declaration
public static void SetUnityRandomState(Random.State state)
Parameters
| Type | Name | Description |
|---|---|---|
| Random.State | state | A |
Shuffle<T>(IRandomSource, IList<T>)
Randomly reorders the elements of list in-place using the
Knuth (Fisher-Yates) shuffle algorithm. The shuffle is unbiased - every permutation
of the list is equally likely.
Declaration
public static void Shuffle<T>(IRandomSource rng, IList<T> list)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to select swap positions. Must not be |
| IList<T> | list | The mutable list to shuffle in-place. Must not be |
Type Parameters
| Name | Description |
|---|---|
| T | The type of elements contained in the list. |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
TryPickOne<T>(IRandomSource, IReadOnlyList<T>, out T)
Attempts to pick a single uniformly random element from the provided list without
throwing if the list is null or empty. Prefer this over PickOne<T>(IRandomSource, IReadOnlyList<T>)
when the list may legitimately be empty at runtime.
Declaration
public static bool TryPickOne<T>(IRandomSource rng, IReadOnlyList<T> list, out T value)
Parameters
| Type | Name | Description |
|---|---|---|
| IRandomSource | rng | The random source used to generate the selection index. Must not be |
| IReadOnlyList<T> | list | The list to pick from. Returns |
| T | value | When this method returns |
Returns
| Type | Description |
|---|---|
| bool |
|
Type Parameters
| Name | Description |
|---|---|
| T | The type of elements contained in the list. |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |
WithUnityRandomState(State, Action)
Temporarily replaces the global UnityEngine.Random state with
state, executes action, and then
restores the previous state - even if action throws.
This is useful for running a deterministic sub-sequence of Unity random calls
without permanently disturbing the ambient Unity random state.
Declaration
public static void WithUnityRandomState(Random.State state, Action action)
Parameters
| Type | Name | Description |
|---|---|---|
| Random.State | state | The |
| Action | action | The delegate to execute while |
Exceptions
| Type | Condition |
|---|---|
| ArgumentNullException | Thrown if |