Wiki

effect · set_variable_to_random

Definition

  • Supported scope:any
  • Supported target:none

Description

sets a variable to a random value. example 
set_variable_to_random = num_dogs #sets num_dogs a random value between [0, 1) 
set_variable_to_random = { 
	var = num_dogs #variable to set 
	min = 5 #default 0. value will be set in between [min, max) 
	max = 10 #default 1. value will be set in between [min, max) 
	integer = yes #default no. if yes the number value will be an integer 
}

Hands-On Notes

Hands-on notes are AI-generated and checked against the vanilla command vocabulary — treat them as a starting point, not authoritative reference. The definition above is the game's own documentation.

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

  1. 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.
  2. 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.