To generate a random number in Unity, use the Random.Range method from the UnityEngine namespace. For an integer, call Random.Range(minInclusive, maxExclusive); for a float, call Random.Range(minInclusive, maxInclusive). This is the standard, built-in way and works in both Update and Start methods.
Understanding Unity’s Random Class
Unity provides its own Random class (not to be confused with System.Random in C#). The core method is Random.Range, which is overloaded for int and float types. The key difference is the upper bound behavior:
- Integer overload:
Random.Range(1, 6)returns 1, 2, 3, 4, or 5 (the max is exclusive). - Float overload:
Random.Range(1.0f, 6.0f)returns any value from 1.0 to 6.0 inclusive (the max is inclusive).
This distinction is a common source of off-by-one errors. For example, to simulate a six-sided die, you call Random.Range(1, 7) for integers, not Random.Range(1, 6).
How to Use Random.Range in a Script
Here’s a minimal C# script that generates a random integer and a random float each frame:
using UnityEngine;
public class RandomExample : MonoBehaviour
{
void Update()
{
// Integer: 0, 1, 2, or 3 (max exclusive)
int randomInt = Random.Range(0, 4);
Debug.Log("Random int: " + randomInt);
// Float: any value from 0.0 to 1.0 inclusive
float randomFloat = Random.Range(0.0f, 1.0f);
Debug.Log("Random float: " + randomFloat);
}
}
Attach this script to any GameObject in your scene. The console will print a new pair of numbers every frame. For a one-time value, place the call in Start() instead.
Choosing Between int and float
Which overload you use depends on your use case:
- Integers are for discrete choices: picking an item from an array, selecting a spawn point, or determining a damage value that is a whole number.
- Floats are for continuous values: random speed, rotation, scale, or color components.
For example, to pick a random element from an array, use Random.Range(0, array.Length) because array.Length is exclusive, giving you valid indices. For a random rotation around the Y axis, use Random.Range(0.0f, 360.0f).
Common Pitfalls and How to Avoid Them
Several mistakes trip up new Unity developers:
- Using System.Random instead of UnityEngine.Random: If you have
using System;at the top of your script,Randombecomes ambiguous. Always useUnityEngine.Randomexplicitly or remove theusing System;line. - Forgetting the ‘f’ suffix on float literals:
Random.Range(0, 1)treats both arguments as integers, so it only returns 0. To get a float, writeRandom.Range(0.0f, 1.0f). - Expecting the max to be inclusive for ints: As noted,
Random.Range(1, 6)never returns 6. This is a deliberate design to match array indexing. - Re-seeding manually: Unity’s random generator is automatically seeded based on the system clock, so you don’t need to seed it. If you want reproducible results for testing, you can set a seed via
Random.InitState(seed), but this affects the global generator.
Seeding and Reproducibility
Sometimes you need the same sequence of random numbers, for example in a procedural level generator or a game replay. Unity provides Random.InitState(int seed) to set the seed. After calling it, the sequence of Random.Range calls will be deterministic for that seed. However, this affects all random calls globally, which can interfere with other systems. A better approach is to use a separate System.Random instance for isolated randomness:
using System;
public class SeededRandom
{
private System.Random rng;
public SeededRandom(int seed)
{
rng = new System.Random(seed);
}
public int Next(int min, int max) // max exclusive
{
return rng.Next(min, max);
}
}
This gives you full control without affecting Unity’s global random state.
Alternatives: Random.Value and Other Methods
Besides Random.Range, Unity offers a few related utilities:
Random.value: Returns a float between 0.0 and 1.0 inclusive. It’s equivalent toRandom.Range(0.0f, 1.0f)but shorter to write.Random.insideUnitCircle: Returns a random point inside a circle of radius 1 (Vector2).Random.insideUnitSphere: Returns a random point inside a sphere of radius 1 (Vector3).Random.onUnitSphere: Returns a random point on the surface of a sphere of radius 1.Random.rotation: Returns a random rotation (Quaternion).
For example, to spawn an object at a random position within a 10-unit radius, you could use Random.insideUnitSphere * 10f.
Performance and Thread Safety
Unity’s Random class is not thread-safe. If you call it from multiple threads (e.g., in a job system or background thread), you will get unpredictable results and potential errors. For parallel code, use Unity.Mathematics.Random from the Mathematics package, which provides a thread-safe random generator that you can seed per thread. For most gameplay code, you only call it on the main thread, so this isn’t a concern. Performance-wise, Random.Range is very fast—millions of calls per frame are possible without noticeable overhead.
Frequently Asked Questions
Why does Random.Range(0, 10) never return 10?
Because the integer overload uses an exclusive upper bound to match array indexing. If you need 0 through 10 inclusive, use Random.Range(0, 11).
Can I use Random.Range in a static method?
Yes, Random.Range is a static method, so you can call it from any static or instance method without needing a reference to a MonoBehaviour.
How do I generate a random number between two floats?
Use Random.Range(minFloat, maxFloat) with float literals, e.g., Random.Range(1.5f, 10.0f). The result is inclusive of both endpoints.
Is Unity’s random truly random?
No, it’s pseudo-random. The sequence is deterministic based on a seed. For most games, this is sufficient. For cryptographic security, use System.Security.Cryptography.RandomNumberGenerator, but that’s rarely needed in games.
What’s the difference between Random.Range and Random.value?
Random.value is a property that returns a float between 0 and 1. Random.Range is a method that can return any range. For a random float between 0 and 1, they are equivalent, but Random.value is slightly more concise.
Related
- Shortcut for cmd? (Open Command Prompt Fast)
- Computer Skills Test for Data Entry: What It Covers
- Generating Random Numbers in Python: A Complete Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Enable an Audit Trail in Excel: Track ChangesTo track edits in Excel for Microsoft 365, save the workbook to OneDrive or SharePoint, then select Review…
- Convert Contact List to Excel: A Step-by-Step GuideTo convert a contact list to Excel, export it from your contacts app as a CSV file, then…
- JavaScript String to Int: parseInt, Number, and MoreFor a JavaScript string that begins with an integer, use parseInt(value, 10); the second argument specifies base 10.…
- How to Remove Duplicates in Excel Safely, Step by StepTo remove duplicate rows in Excel for Microsoft 365 on Windows, select a cell in your data, choose…
- Budget Spreadsheet With Rollover: How It WorksA budget spreadsheet with rollover carries an unspent category balance into the next month. In Excel for Microsoft…
- Circular Reference Settings in Excel: How They WorkIn Excel for Microsoft 365 on Windows, turn on circular-reference calculations at File > Options > Formulas by…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.