Random number generation utils for the Godot 4
- Random integer range
- Random float range
- Random item(s) from an array
- Random item(s) from an array with weighted
- Clone or download a copy of this repository.
- Enable the addon in the project settings.
- Restart Godot IDE.
int_range(from: int, to: int, rng: RandomNumberGenerator = null) -> int
Returns a pseudo-random integer between from and to (inclusive)
RngUtils.int_range(1, 100)
# output: 89
float_range(from: float, to: float, rng: RandomNumberGenerator = null)
Returns a pseudo-random float between from and to (inclusive)
RngUtils.float_range(0.1, 5.1)
# output: 3.89661073684692
array(array: Array, num: int = 1, unique: bool = false, rng: RandomNumberGenerator = null) -> Array
Returns one or multiple random items from an array
var array := ["a", "b", "c", "d"]
# random one item
RngUtils.array(array)
# output: ["a"]
# random four items(not unique)
RngUtils.array(array, 4)
# output: ["d", "d", "d", "c"]
# random four items(unique)
RngUtils.array(array, 4, true)
# output: ["c", "b", "a", "d"]
array_with_weighted(weights: Array[Dictionary], num: int = 1, unique: bool = false, rng: RandomNumberGenerator = null) -> Array[Dictionary]
- Dictionary key
weight
require - Returns one or multiple random items from an array with weighted
var weights: Array[Dictionary] = [
{"value":"a","txt": "apple", "weight": 5.0},
{"value":"b", "weight": 10.0},
{"value":"c", "weight": 20.0},
{"value":"d", "weight": 40.0},
{"value":"e", "weight": 25.0},
]
# random one item
RngUtils.array_with_weighted(weights, 1)
# output: [{ "value": "c", "weight": 20 }]
# random four items(not unique)
RngUtils.array_with_weighted(weights, 4)
# output: [{ "value": "c", "weight": 20 }, { "value": "d", "weight": 40 }, { "value": "e", "weight": 25 }, { "value": "d", "weight": 40 }]
# random four items(unique)
RngUtils.array_with_weighted(weights, 4, true)
# output: { "value": "d", "weight": 40 }, { "value": "c", "weight": 20 }, { "value": "a", "txt": "apple", "weight": 5 }, { "value": "b", "weight": 10 }]