Random number generation

Many games rely on randomness to implement core game mechanics. This page guides you through common types of randomness and how to implement them in Godot.

After giving you a brief overview of useful functions that generate random numbers, you will learn how to get random elements from arrays, dictionaries, and how to use a noise generator in GDScript. Lastly, we’ll take a look at cryptographically secure random number generation and how it differs from typical random number generation.

Note

Computers cannot generate “true” random numbers. Instead, they rely on pseudorandom number generators (PRNGs).

Godot internally uses the PCG Family of pseudorandom number generators.

Global scope versus RandomNumberGenerator class

Godot exposes two ways to generate random numbers: via global scope methods or using the RandomNumberGenerator class.

Global scope methods are easier to set up, but they don’t offer as much control.

RandomNumberGenerator requires more code to use, but allows creating multiple instances, each with their own seed and state.

This tutorial uses global scope methods, except when the method only exists in the RandomNumberGenerator class.

The randomize() method

Note

Since Godot 4.0, the random seed is automatically set to a random value when the project starts. This means you don’t need to call randomize() in _ready() anymore to ensure that results are random across project runs. However, you can still use randomize() if you want to use a specific seed number, or generate it using a different method.

In global scope, you can find a randomize() method. This method should be called only once when your project starts to initialize the random seed. Calling it multiple times is unnecessary and may impact performance negatively.

Putting it in your main scene script’s _ready() method is a good choice:

GDScriptC#

  1. func _ready():
  2. randomize()
  1. public override void _Ready()
  2. {
  3. GD.Randomize();
  4. }

You can also set a fixed random seed instead using seed(). Doing so will give you deterministic results across runs:

GDScriptC#

  1. func _ready():
  2. seed(12345)
  3. # To use a string as a seed, you can hash it to a number.
  4. seed("Hello world".hash())
  1. public override void _Ready()
  2. {
  3. GD.Seed(12345);
  4. // To use a string as a seed, you can hash it to a number.
  5. GD.Seed("Hello world".Hash());
  6. }

When using the RandomNumberGenerator class, you should call randomize() on the instance since it has its own seed:

GDScriptC#

  1. var random = RandomNumberGenerator.new()
  2. random.randomize()
  1. var random = new RandomNumberGenerator();
  2. random.Randomize();

Getting a random number

Let’s look at some of the most commonly used functions and methods to generate random numbers in Godot.

The function randi() returns a random number between 0 and 2^32 - 1. Since the maximum value is huge, you most likely want to use the modulo operator (%) to bound the result between 0 and the denominator:

GDScriptC#

  1. # Prints a random integer between 0 and 49.
  2. print(randi() % 50)
  3. # Prints a random integer between 10 and 60.
  4. print(randi() % 51 + 10)
  1. // Prints a random integer between 0 and 49.
  2. GD.Print(GD.Randi() % 50);
  3. // Prints a random integer between 10 and 60.
  4. GD.Print(GD.Randi() % 51 + 10);

randf() returns a random floating-point number between 0 and 1. This is useful to implement a Weighted random probability system, among other things.

randfn() returns a random floating-point number following a normal distribution. This means the returned value is more likely to be around the mean (0.0 by default), varying by the deviation (1.0 by default):

GDScriptC#

  1. # Prints a random floating-point number from a normal distribution with a mean 0.0 and deviation 1.0.
  2. print(randfn())
  1. // Prints a random floating-point number from a normal distribution with a mean of 0.0 and deviation of 1.0.
  2. GD.Print(GD.Randfn());

randf_range() takes two arguments from and to, and returns a random floating-point number between from and to:

GDScriptC#

  1. # Prints a random floating-point number between -4 and 6.5.
  2. print(randf_range(-4, 6.5))
  1. // Prints a random floating-point number between -4 and 6.5.
  2. GD.Print(GD.RandfRange(-4, 6.5));

randi_range() takes two arguments from and to, and returns a random integer between from and to:

GDScriptC#

  1. # Prints a random integer between -10 and 10.
  2. print(randi_range(-10, 10))
  1. // Prints a random integer between -10 and 10.
  2. GD.Print(GD.RandiRange(-10, 10));

Get a random array element

We can use random integer generation to get a random element from an array, or use the Array.pick_random method to do it for us:

GDScriptC#

  1. var _fruits = ["apple", "orange", "pear", "banana"]
  2. func _ready():
  3. for i in range(100):
  4. # Pick 100 fruits randomly.
  5. print(get_fruit())
  6. for i in range(100):
  7. # Pick 100 fruits randomly, this time using the `Array.pick_random()`
  8. # helper method. This has the same behavior as `get_fruit()`.
  9. print(_fruits.pick_random())
  10. func get_fruit():
  11. var random_fruit = _fruits[randi() % _fruits.size()]
  12. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  13. # We may get the same fruit multiple times in a row.
  14. return random_fruit
  1. // Use Godot's Array type instead of a BCL type so we can use `PickRandom()` on it.
  2. private Godot.Collections.Array<string> _fruits = new Godot.Collections.Array<string> { "apple", "orange", "pear", "banana" };
  3. public override void _Ready()
  4. {
  5. for (int i = 0; i < 100; i++)
  6. {
  7. // Pick 100 fruits randomly.
  8. GD.Print(GetFruit());
  9. }
  10. for (int i = 0; i < 100; i++)
  11. {
  12. // Pick 100 fruits randomly, this time using the `Array.PickRandom()`
  13. // helper method. This has the same behavior as `GetFruit()`.
  14. GD.Print(_fruits.PickRandom());
  15. }
  16. }
  17. public string GetFruit()
  18. {
  19. string randomFruit = _fruits[GD.Randi() % _fruits.Size()];
  20. // Returns "apple", "orange", "pear", or "banana" every time the code runs.
  21. // We may get the same fruit multiple times in a row.
  22. return randomFruit;
  23. }

To prevent the same fruit from being picked more than once in a row, we can add more logic to the above method. In this case, we can’t use Array.pick_random since it lacks a way to prevent repetition:

GDScriptC#

  1. var _fruits = ["apple", "orange", "pear", "banana"]
  2. var _last_fruit = ""
  3. func _ready():
  4. # Pick 100 fruits randomly.
  5. for i in range(100):
  6. print(get_fruit())
  7. func get_fruit():
  8. var random_fruit = _fruits[randi() % _fruits.size()]
  9. while random_fruit == _last_fruit:
  10. # The last fruit was picked. Try again until we get a different fruit.
  11. random_fruit = _fruits[randi() % _fruits.size()]
  12. # Note: if the random element to pick is passed by reference,
  13. # such as an array or dictionary,
  14. # use `_last_fruit = random_fruit.duplicate()` instead.
  15. _last_fruit = random_fruit
  16. # Returns "apple", "orange", "pear", or "banana" every time the code runs.
  17. # The function will never return the same fruit more than once in a row.
  18. return random_fruit
  1. private string[] _fruits = { "apple", "orange", "pear", "banana" };
  2. private string _lastFruit = "";
  3. public override void _Ready()
  4. {
  5. for (int i = 0; i < 100; i++)
  6. {
  7. // Pick 100 fruits randomly.
  8. GD.Print(GetFruit());
  9. }
  10. }
  11. public string GetFruit()
  12. {
  13. string randomFruit = _fruits[GD.Randi() % _fruits.Length];
  14. while (randomFruit == _lastFruit)
  15. {
  16. // The last fruit was picked. Try again until we get a different fruit.
  17. randomFruit = _fruits[GD.Randi() % _fruits.Length];
  18. }
  19. _lastFruit = randomFruit;
  20. // Returns "apple", "orange", "pear", or "banana" every time the code runs.
  21. // The function will never return the same fruit more than once in a row.
  22. return randomFruit;
  23. }

This approach can be useful to make random number generation feel less repetitive. Still, it doesn’t prevent results from “ping-ponging” between a limited set of values. To prevent this, use the shuffle bag pattern instead.

Get a random dictionary value

We can apply similar logic from arrays to dictionaries as well:

GDScript

  1. var metals = {
  2. "copper": {"quantity": 50, "price": 50},
  3. "silver": {"quantity": 20, "price": 150},
  4. "gold": {"quantity": 3, "price": 500},
  5. }
  6. func _ready():
  7. for i in range(20):
  8. print(get_metal())
  9. func get_metal():
  10. var random_metal = metals.values()[randi() % metals.size()]
  11. # Returns a random metal value dictionary every time the code runs.
  12. # The same metal may be selected multiple times in succession.
  13. return random_metal

Weighted random probability

The randf() method returns a floating-point number between 0.0 and 1.0. We can use this to create a “weighted” probability where different outcomes have different likelihoods:

GDScriptC#

  1. func _ready():
  2. for i in range(100):
  3. print(get_item_rarity())
  4. func get_item_rarity():
  5. var random_float = randf()
  6. if random_float < 0.8:
  7. # 80% chance of being returned.
  8. return "Common"
  9. elif random_float < 0.95:
  10. # 15% chance of being returned.
  11. return "Uncommon"
  12. else:
  13. # 5% chance of being returned.
  14. return "Rare"
  1. public override void _Ready()
  2. {
  3. for (int i = 0; i < 100; i++)
  4. {
  5. GD.Print(GetItemRarity());
  6. }
  7. }
  8. public string GetItemRarity()
  9. {
  10. float randomFloat = GD.Randf();
  11. if (randomFloat < 0.8f)
  12. {
  13. // 80% chance of being returned.
  14. return "Common";
  15. }
  16. else if (randomFloat < 0.95f)
  17. {
  18. // 15% chance of being returned.
  19. return "Uncommon";
  20. }
  21. else
  22. {
  23. // 5% chance of being returned.
  24. return "Rare";
  25. }
  26. }

You can also get a weighted random index using the rand_weighted() method on a RandomNumberGenerator instance. This returns a random integer between 0 and the size of the array that is passed as a parameter. Each value in the array is a floating-point number that represents the relative likelihood that it will be returned as an index. A higher value means the value is more likely to be returned as an index, while a value of 0 means it will never be returned as an index.

For example, if [0.5, 1, 1, 2] is passed as a parameter, then the method is twice as likely to return 3 (the index of the value 2) and twice as unlikely to return 0 (the index of the value 0.5) compared to the indices 1 and 2.

Since the returned value matches the array’s size, it can be used as an index to get a value from another array as follows:

GDScriptC#

  1. # Prints a random element using the weighted index that is returned by `rand_weighted()`.
  2. # Here, "apple" will be returned twice as rarely as "orange" and "pear".
  3. # "banana" is twice as common as "orange" and "pear", and four times as common as "apple".
  4. var fruits = ["apple", "orange", "pear", "banana"]
  5. var probabilities = [0.5, 1, 1, 2];
  6. var random = RandomNumberGenerator.new()
  7. print(fruits[random.rand_weighted(probabilities)])
  1. // Prints a random element using the weighted index that is returned by `RandWeighted()`.
  2. // Here, "apple" will be returned twice as rarely as "orange" and "pear".
  3. // "banana" is twice as common as "orange" and "pear", and four times as common as "apple".
  4. string[] fruits = { "apple", "orange", "pear", "banana" };
  5. float[] probabilities = { 0.5, 1, 1, 2 };
  6. var random = new RandomNumberGenerator();
  7. GD.Print(fruits[random.RandWeighted(probabilities)]);

“Better” randomness using shuffle bags

Taking the same example as above, we would like to pick fruits at random. However, relying on random number generation every time a fruit is selected can lead to a less uniform distribution. If the player is lucky (or unlucky), they could get the same fruit three or more times in a row.

You can accomplish this using the shuffle bag pattern. It works by removing an element from the array after choosing it. After multiple selections, the array ends up empty. When that happens, you reinitialize it to its default value:

  1. var _fruits = ["apple", "orange", "pear", "banana"]
  2. # A copy of the fruits array so we can restore the original value into `fruits`.
  3. var _fruits_full = []
  4. func _ready():
  5. _fruits_full = _fruits.duplicate()
  6. _fruits.shuffle()
  7. for i in 100:
  8. print(get_fruit())
  9. func get_fruit():
  10. if _fruits.is_empty():
  11. # Fill the fruits array again and shuffle it.
  12. _fruits = _fruits_full.duplicate()
  13. _fruits.shuffle()
  14. # Get a random fruit, since we shuffled the array,
  15. # and remove it from the `_fruits` array.
  16. var random_fruit = _fruits.pop_front()
  17. # Prints "apple", "orange", "pear", or "banana" every time the code runs.
  18. return random_fruit

When running the above code, there is a chance to get the same fruit twice in a row. Once we picked a fruit, it will no longer be a possible return value unless the array is now empty. When the array is empty, we reset it back to its default value, making it possible to have the same fruit again, but only once.

Random noise

The random number generation shown above can show its limits when you need a value that slowly changes depending on the input. The input can be a position, time, or anything else.

To achieve this, you can use random noise functions. Noise functions are especially popular in procedural generation to generate realistic-looking terrain. Godot provides FastNoiseLite for this, which supports 1D, 2D and 3D noise. Here’s an example with 1D noise:

GDScriptC#

  1. var _noise = FastNoiseLite.new()
  2. func _ready():
  3. # Configure the FastNoiseLite instance.
  4. _noise.noise_type = FastNoiseLite.NoiseType.TYPE_SIMPLEX_SMOOTH
  5. _noise.seed = randi()
  6. _noise.fractal_octaves = 4
  7. _noise.frequency = 1.0 / 20.0
  8. for i in 100:
  9. # Prints a slowly-changing series of floating-point numbers
  10. # between -1.0 and 1.0.
  11. print(_noise.get_noise_1d(i))
  1. private FastNoiseLite _noise = new FastNoiseLite();
  2. public override void _Ready()
  3. {
  4. // Configure the FastNoiseLite instance.
  5. _noise.NoiseType = NoiseTypeEnum.SimplexSmooth;
  6. _noise.Seed = (int)GD.Randi();
  7. _noise.FractalOctaves = 4;
  8. _noise.Frequency = 1.0f / 20.0f;
  9. for (int i = 0; i < 100; i++)
  10. {
  11. GD.Print(_noise.GetNoise1D(i));
  12. }
  13. }

Cryptographically secure pseudorandom number generation

So far, the approaches mentioned above are not suitable for cryptographically secure pseudorandom number generation (CSPRNG). This is fine for games, but this is not sufficient for scenarios where encryption, authentication or signing is involved.

Godot offers a Crypto class for this. This class can perform asymmetric key encryption/decryption, signing/verification, while also generating cryptographically secure random bytes, RSA keys, HMAC digests, and self-signed X509Certificates.

The downside of CSPRNG is that it’s much slower than standard pseudorandom number generation. Its API is also less convenient to use. As a result, CSPRNG should be avoided for gameplay elements.

Example of using the Crypto class to generate 2 random integers between 0 and 2^32 - 1 (inclusive):

  1. var crypto := Crypto.new()
  2. # Request as many bytes as you need, but try to minimize the amount
  3. # of separate requests to improve performance.
  4. # Each 32-bit integer requires 4 bytes, so we request 8 bytes.
  5. var byte_array := crypto.generate_random_bytes(8)
  6. # Use the ``decode_u32()`` method from PackedByteArray to decode a 32-bit unsigned integer
  7. # from the beginning of `byte_array`. This method doesn't modify `byte_array`.
  8. var random_int_1 := byte_array.decode_u32(0)
  9. # Do the same as above, but with an offset of 4 bytes since we've already decoded
  10. # the first 4 bytes previously.
  11. var random_int_2 := byte_array.decode_u32(4)
  12. prints("Random integers:", random_int_1, random_int_2)

See also

See PackedByteArray‘s documentation for other methods you can use to decode the generated bytes into various types of data, such as integers or floats.


User-contributed notes

Please read the User-contributed notes policy before submitting a comment.

Previous Next