Random numbers are essential for everything from procedural generation to enemy AI and loot drops. In Godot, you generate them with the RandomNumberGenerator class (or the global randf()/randi() functions). The key is to seed the generator once, then call its methods to get floats, integers, or values from a range. This guide shows you the correct way, avoids common pitfalls, and includes troubleshooting for when randomness behaves unexpectedly.
What You’ll Need
- Godot 3.x or 4.x (steps work in both, with minor syntax notes)
- A project with any script (GDScript) where you want randomness
Step-by-Step
- Create a RandomNumberGenerator instance. In GDScript, add a variable at the top of your script:
var rng = RandomNumberGenerator.new(). This gives you a dedicated generator object. - Seed the generator (optional but recommended). Call
rng.seed = hash("your_string")orrng.randomize().randomize()uses the current time as a seed, making each run different. If you want reproducible results (e.g., for testing), set a fixed number:rng.seed = 12345. - Generate a random float between 0 and 1. Use
var my_float = rng.randf(). This returns a value like 0.374, inclusive of 0 but exclusive of 1. - Generate a random integer. Use
var my_int = rng.randi(). This returns a 32-bit unsigned integer (0 to 4,294,967,295). - Generate an integer within a specific range. Use
rng.randi_range(min, max). For example,var dice = rng.randi_range(1, 6)gives 1, 2, 3, 4, 5, or 6. Both bounds are inclusive. - Generate a float within a specific range. Use
rng.randf_range(min, max). For example,var speed = rng.randf_range(100.0, 200.0)gives a float between 100.0 and 200.0 (inclusive of min, exclusive of max). - Use the global functions (alternative). If you don’t need a persistent generator, you can call
randf(),randi(),randi_range(), andrandf_range()directly. These use a global generator that is automatically seeded at game start, but you can also callrandomize()once to reseed it. - Shuffle an array. Use
array.shuffle()to randomly reorder elements in place. For a new shuffled copy, duplicate first:var shuffled = array.duplicate(); shuffled.shuffle(). - Pick a random element from an array. Use
array[randi() % array.size()](but see the Common Mistakes section for bias) or better, usearray[randi_range(0, array.size() - 1)].
Common Mistakes
- Using
%for ranges.randi() % 10gives a biased result because the maximum value (2^32) is not a multiple of 10. Always userandi_range()orrandf_range(). - Forgetting to seed. If you never call
randomize()or set a seed, the generator starts with the same default seed, so you get the same sequence every run. This is useful for debugging but not for gameplay. - Creating a new generator every frame. If you create a
RandomNumberGeneratorin_process()and seed it with time, you might get similar values because time changes slowly. Reuse one instance. - Using
randi() % nwhen n is large. Same bias issue as above; userandi_range(). - Assuming
randf()returns 1.0. It never does; it’s in [0, 1). If you need 1 inclusive, userandf_range(0, 1)but note that max is exclusive.
Tips
- Seed once per game instance. Call
randomize()in_ready()of your main scene, or set a fixed seed for level generation so you can reproduce the same level for testing. - Use
randi_range()for inclusive integer ranges. It’s clearer and avoids off-by-one errors. - For weighted random choices, create an array of items and use
randf()to pick based on cumulative probabilities. Example: if item A has 70% chance, item B 30%, generatevar roll = rng.randf()and ifroll < 0.7choose A else B. - For random positions, combine
randf_range()with vector math:var pos = Vector2(randf_range(0, screen_width), randf_range(0, screen_height)). - In GDScript, you can also use
randfn(mean, stddev)for a normal distribution. This is available on the RNG instance in Godot 4.x, but not in 3.x.
Troubleshooting
- You get the same numbers every time. You didn't seed the generator. Call
rng.randomize()orrandomize()once before generating. - Your random numbers are biased (some values appear more). You likely used
%withrandi(). Switch torandi_range(). - You get an error like "Invalid call. Nonexistent function 'randi_range' in base 'RandomNumberGenerator'." This happens in Godot 3.x; the function is named
randi() % rangeor you need to userand_range()for floats. In Godot 3, userandi() % (max - min + 1) + min(but be aware of bias) or use the globalrandi_range()which exists in 3.1+? Actually,randi_range()was added in Godot 3.1. If you're on 3.0, userandi() % (max - min + 1) + min. - Your random floats are always the same range. Make sure you're using
randf_range()and notrandf()which always returns [0,1). - Shuffling doesn't change the array.
shuffle()works in-place. If you want to keep the original, duplicate first.
Frequently Asked Questions
- What's the difference between
RandomNumberGeneratorand the globalrandf()? The global functions use a single shared generator. Creating your own instance lets you have independent sequences and control seeding per context (e.g., one for gameplay, one for audio). - How do I get a random boolean? Use
rng.randi_range(0, 1) == 1orrng.randf() < 0.5. - Can I save the seed to reproduce a random sequence later? Yes, store the seed value and set it again:
rng.seed = saved_seed. Then the sequence repeats. - Is there a way to get a random number without a generator object? Yes, call
randf(),randi(),randi_range(), etc., directly. They use the global generator. - Why does
randi()return such a huge number? It returns a 32-bit unsigned integer. Userandi_range()to get a number in a practical range. - How do I generate a random color? Use
Color(randf(), randf(), randf())for RGB, or include alpha:Color(randf(), randf(), randf(), 1.0).
Related
- Remove Duplicates in Google Sheets: Formula & Steps
- SUMIF Dropdown in Google Sheets: How to Use
- Data Entry Pay Per Entry: Rates & Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Merge Cells in Excel: How to Keep All Your DataNo: in Microsoft Excel, merging cells keeps only the value in the upper-left cell and discards the contents…
- How Much Coding for Data Visualization?You need surprisingly little coding for most data visualization tasks: basic charts in Excel, Google Sheets, or Tableau…
- Excel Protect Sheet: How It Works and How to Use ItIn Excel for Microsoft 365 on Windows, Protect Sheet restricts what people can change on a worksheet; it…
- How to Convert an Excel Table to Word Without Losing LayoutTo convert an Excel table to Word, select and copy the cells in Excel, then paste them into…
- How to Edit Border Color in Excel: Step-by-Step GuideTo edit a cell border color in Excel for Microsoft 365 on Windows, select the cells, open Home…
- How to Insert a Row in Excel: Steps, Shortcuts & TipsTo insert a row in Excel for Microsoft 365 on Windows, select the row number where the new…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.