Get a random number between a min and max amount

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Newby

I am randomizing my enemy hp and speed for more variation so i made a script to get their random values with a min and max amount. It is a bit long for what it is supposed to do.

func _ready():
var hp = randi() % MAX_HP + 1
var speed = randi() % MAX_SPEED + 1
if hp < MIN_HP:
	hp += MIN_HP
if speed < MIN_SPEED:
	speed += MIN_SPEED
HP = hp
MAX_SPEED = speed

Is their a better method in choosing a random number between a min and max amount

:bust_in_silhouette: Reply From: kidscancode

Assuming you wanted an integer, randi() is fine.

# random number between MIN and MAX:
var n = randi() % (MAX - MIN) + MIN

Alternatively, you can use the randi_range() function provided by RandomNumberGenerator:

var random =

func _ready():
	var n = random.randi_range(MIN, MAX)

Performance wise which one would be better?

Newby | 2020-02-12 02:01

That’s not even worth asking. Performance is not something to worry about - just write your code. Worry about performance when you actually encounter something that impacts performance, if you ever do. And if you do, your random number code is not going to be it.

kidscancode | 2020-02-12 02:54

Actually it should be modulo (MAX - MIN + 1). Otherwise you never will get MAX as a result. RandomGenerator does the same thing. As this is currently selected as best answer, you should consider editing it. Also note that this method tends to be biased.

njamster | 2020-02-12 14:06

:bust_in_silhouette: Reply From: Sween123

Put your code of randomizing into a function:

func random_int(Min, Max):
	var value = randi() % (Max - Min + 1) + Min
	return value