Random Numbers in GDScript

Our random number generation example demonstrates how to generate pseudorandom numbers in GDScript.

extends Node

func _ready():
    # Generate a random integer between 0 and 99 (inclusive)
    print(randi() % 100, ",", randi() % 100)
    print()

    # Generate a random float between 0.0 and 1.0
    print(randf())

    # Generate a random float between 5.0 and 10.0
    print(randf_range(5.0, 10.0), ",", randf_range(5.0, 10.0))
    print()

    # Create a new RandomNumberGenerator with a fixed seed
    var rng = RandomNumberGenerator.new()
    rng.seed = 42
    print(rng.randi() % 100, ",", rng.randi() % 100)
    print()

    # Create another RandomNumberGenerator with the same seed
    var rng2 = RandomNumberGenerator.new()
    rng2.seed = 42
    print(rng2.randi() % 100, ",", rng2.randi() % 100)
    print()

In GDScript, we use built-in functions for random number generation. The randi() function generates random integers, while randf() generates random floats between 0 and 1.

For generating random integers within a specific range, we use the modulo operator (%) with randi(). For example, randi() % 100 gives a random integer between 0 and 99.

The randf_range(from, to) function is used to generate random floats within a specific range.

To create a random number generator with a fixed seed, we use the RandomNumberGenerator class. This allows us to generate reproducible sequences of random numbers.

When you run this script, you might see output similar to this:

68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

Note that the actual numbers may be different each time you run the script, except for the last two lines which use a fixed seed.

GDScript’s random number generation is suitable for most game development needs. For more advanced randomization techniques or cryptographically secure random numbers, you might need to implement custom solutions or use external libraries.

Remember that the random number generation in GDScript, like in most programming languages, is pseudorandom. For truly random numbers, you would need to use hardware random number generators or external sources of entropy.