Hands-On Usage
set_variable_to_random is commonly used in mods to introduce randomness into scenarios such as randomizing a country's initial resource stockpiles, randomly determining numerical rewards for events, or adding unpredictable weights to AI behavior. The example below demonstrates how to randomly assign a supply bonus between 5 and 10 to the player in an event:
country_event = {
id = my_mod.1
immediate = {
set_variable_to_random = {
var = random_supply_bonus
min = 5
max = 10
integer = yes
}
add_to_variable = {
var = supply_stockpile
value = random_supply_bonus
}
}
}
Synergy
[add_to_variable](/wiki/effect/add_to_variable) — After generating a random value, it typically needs to be accumulated into an existing variable rather than directly overwriting it.
[clamp_variable](/wiki/effect/clamp_variable) — Random values may fall outside the reasonable bounds of your game logic after being written; use this command to constrain the result within a safe range.
[check_variable](/wiki/trigger/check_variable) — Read the newly set random variable within a trigger block and decide subsequent branching logic based on its value.
[if](/wiki/effect/if) — Combined with check_variable, perform conditional checks on random results to achieve a "probabilistic branching" effect.
Common Pitfalls
max is an open interval: The range is [min, max), meaning the result will never reach max itself. If you want an integer result to include 10, set max to 11 rather than 10; otherwise, with integer = yes the maximum generated will only be 9.
- Forgetting
integer = yes causes floating-point contamination: By default, a floating-point number is returned. If subsequent scripts use this variable for division or display it to players, the decimal portion may cause unexpected numerical errors or localization display issues. Be explicit by declaring integer = yes or use [round_variable](/wiki/effect/round_variable) afterward to round the value.