0 votes

I try to generate a random number using the randi_range() function like this:

var rng = RandomNumberGenerator.new()
var number = rng.randi_range(0, 5)

func _ready():
    print(number)

But everytime I run this code, the console always displays the maxinum number 5. Is there something wrong with my usage of the function?

Godot version v3.2.3
in Engine by (24 points)

I think u need to include a call to rng.randomize()

1 Answer

+1 vote
Best answer

You need to rnd.randomize() first.

by (1,402 points)
selected by

Where to put it?

var rng : RandomNumberGenerator = RandomNumberGenerator.new()
var number : int  = 0

func _ready() -> void:
    rng.randomize()
    number = rng.randi_range(0, 5)
    print(number)

EDIT 1:
If you need just a random number, and not a whole generator you can also do it like this:

var number : int  = 0

func _ready() -> void:
    randomize()
    number = randi() % 6 # generates random integers between 0 and 5
    #number = 5 + randi() % 11 # generates random integers between 5 and 15
    print(number)

EDIT 2:
You could also code your own function for that:

var number : int  = 0

func _ready() -> void:
    randomize()
    number = randi_range(0, 5)
    print(number)

func randi_range(a : int, b : int) -> int:
    assert(b > a, "b must be greater than a!")
    return a + randi() % (b + 1 - a)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.

Categories