Choose Random From Range in Array

Godot Version

v4.6.2

Question

Good evening. I have a fully working script that pulls one random number from multiple arrays based on certain conditions. The way I’ve done it is by listing out a bunch of numbers, but I would like to simplify my code by using a range, because all of these numbers are sequential. I’m not sure how I would go about doing this, but I assume it uses the range function. Apologies if this is something that has been asked before, but I couldn’t find anything about this very specific thing on the internet.

Thanks

Use randi_range()

1 Like

If you’re trying to pick from multiple Arrays and you’re ok with all the Arrays having equal weighting, you could also us pick_random() on each Array, put each result into a temporary Array, and the run pick_random() on that Array for the final result.

func _ready() -> void:
	var deck: Array = [
		"Card 1",
		"Card 2",
		"Card 3",
		"Card 4",
		]
	var stuff: Array = [
		"Stuff 1",
		"Stuff 2"
	]
	var array_list: Array
	array_list.append(deck)
	array_list.append(stuff)
	var temp_array: Array
	for array: Array in array_list:
		temp_array.append(array.pick_random())
	print("Final result: %s" % temp_array.pick_random())

You can add this to a Node and press Run Current Scene (F6) to see it working.

1 Like

*Simple way :

if it s numbers *
var numbers = range(10, 21) # 10 to 20 inclusive
var random_number = numbers.pick_random()

var* deck = [“Card 1”, “Card 2”, “Card 3”, “Card 4”]
var random_card = deck.pick_random()

Don’t forget to call randomize() in ready() for better random results.

1 Like

Thank you all