Rand.Range returning the same number every time

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Crows
:warning: Old Version Published before Godot 3 was released.

I’m trying to make a simple map generator for a Roguelite-like. I wanted to start randomly spawning one room, but for some reason with this code Rand.Range returns 2.176614 every time. If I comment out all the references to gameRunning it starts returning numbers between 0 and 3 like it’s supposed to. Does anyone know why it does this?

var roomCount = 0
var gameRunning = false


func _ready():
	set_process(true)
	gameRunning = true
	
func _process(delta):
	if (gameRunning == true):
		print("start if loop")
		var number = rand_range(0,3)
		print(str(number))
		if number <= 1:
			var roomInstance = room1.instance()
			add_child(roomInstance)
			roomInstance.set_owner(self)
			roomInstance.set_pos(Vector2(0, 0))
			roomCount = 1
		elif number <= 2:
			var roomInstance = room2.instance()
			add_child(roomInstance)
			roomInstance.set_owner(self)
			roomInstance.set_pos(Vector2(0, 0))
			roomCount = 2
		elif number <= 3:
			var roomInstance = room3.instance()
			add_child(roomInstance)
			roomInstance.set_owner(self)
			roomInstance.set_pos(Vector2(0, 0))
			roomCount = 3
		print('Roomcount: ' + str(roomCount))
		gameRunning = false
:bust_in_silhouette: Reply From: Ace-Dragon

For the float problem, you can use something like int(value) to make a variable only express itself in integers.

:bust_in_silhouette: Reply From: Shin-NiL

You should call randomize() function to generate a new seed each time.

Indeed. Just call randomize() once in a _ready() function, likely in a global script or the script attached to your main scene.

Akien | 2016-03-04 09:27

Cool. Thanks. :slight_smile:

Crows | 2016-03-05 14:36

Thanks! I was always confused about this.

blue_robin | 2022-01-17 18:45