I dont remember what language it was but you could do random(1,10) or something like that and it would pick a number between 1 to 10, is there a way to do something like this in gdscript?

+55 votes

Best answer

`randi()%10+1`

returns an `int`

from 1 to 10

`randf()*10.0+1.0`

returns a `float`

from 1.0 to 10.999999~

`rand_range(1,11)`

returns a `float`

from 1.0 to 10.999999~

`range(1,11)[randi()%range(1,11).size()]`

is a little ugly and less efficient but returns an `int`

from 1 to 10 without you having to do the math yourself (aka the 11+1 part) because all you need to do is set the range()

To get a random integer between 1 and 10, I find it more intuitive to floor the random float in range. More specifically:

floor(rand_range(1, 11))

I'm trying to generate a random between 10-30 (randi()%30+10) but it's giving me a 35. Probably doing it wrong, but can't figure out how to make it right.

This answer has an important error. If you want to produce a real number in the interval [x,y[, in general you use:

```
(randf() * (y-x)) + x.
```

From 1 to 10, you have `randf() * 9 + 1`

. This is because `randf()`

can be 1 as maximum. In this case, you would obtain 9 + 1 = 10. In the case proposed by this answer, `randf() * 11 + 1`

, if by chance `randf()`

turns out to be greater than 0.8 you get something greater than 10. So, there is a 20% chance of having a wrong answer.

randi()%11+1 returns an int from 1 to **11**

If you someone needs a random int between 1 and 10, use:

randi()%**10**+1

+19 votes

+6 votes

As of Godot 3:

`randi() % 20`

returns an int from 0 to 19

`randi() % 20 + 1`

returns an int from 1 to 20

`randf()`

returns a float from 0 to 1

Unfortunately, the older style no longer seems to work.

+3 votes

The following code returns a random number, but it is the **same** number each time the script is executed:

```
var random_value = rand_range(1,10)
```

The following code gives you **different** random numbers each time the script is executed:

```
var random_generator = RandomNumberGenerator.new()
random_generator.randomize()
var random_value = random_generator.randf_range(1,10)
```

https://docs.godotengine.org/en/stable/classes/class_randomnumbergenerator.html

or simply:

```
randomize()
var random_value = rand_range(1,10)
```

- All categories
- Engine 15,749
- Projects 1,865
- Gossip 257

Answer changed due to more info