Random numbers are very useful in games and generating them is usually a single line of code. In this tutorial, we will see how to generate random numbers in Godot and see the available functions.
I am using Godot 3.4.2 for this tutorial.
To generate a random number in Godot you need to initialize a variable of type RandomNumberGenerator as shown below
You can set the seed if you want but it’s completely optional. Seed can be set as shown below
You can also set a random seed based on time using
Once initialized you can generate random numbers using the following functions
|randf()||Generates a random float between 0 and 1|
|randf_range()||Generates a random float in the given range|
|randi()||Generates a random integer|
|randi_range()||Generates a random int in the given range.|
Here is a sample script to generate random numbers in Godot
extends Node2D var rand=RandomNumberGenerator.new() func _ready(): rand.randomize() print(rand.randf())