September 21, 2020

soltveit.org

..Geekish..

Unity random number with examples

Unity Random Number

How to do a Unity random number for integers and float. Let us go thru a few examples with random integer and random float using unity random range. To get a random number is an important part of almost every game.

Unity random number: integer

The range of int we will use in this example is from 0 to 10. We want to include 10 as a possible number to get. Let us draw 9 random numbers and have a look to see what they look like. I have created an empty game object to the scene and attached this little script.

Here is the script to create unity random number from 0 to 10.

using UnityEngine;

public class RandomNumber : MonoBehaviour
{
    void Start()
    {
        int a;

        for (int x = 0; x < 10; x++)
        {
            a = Random.Range(0, 11); // min = 0, max = 11
            Debug.Log(a);            // return numbers from 0 to 10
        }
    }
}

This is what our output looks like.

If you run this several times you will get a different result every time. If you need to have the same procedure of random numbers, you will need to check out Random Seeds.

How to get float instead of integer

We will use the same project as we only need to make a small change in the script to make it generate random floats instead of integers. We also change the max number to 10 instead of 11. Here is the updated script snippet.

using UnityEngine;

public class RandomNumber : MonoBehaviour
{
    void Start()
    {
        float a;

        for (int x = 0; x < 10; x++)
        {
            a = Random.Range(0f, 10f); // Min = 0, Max = 10
            Debug.Log(a);              // returns numbers from 0 to 10
        }
    }
}

We just declare the variable as float instead of integer. And add an f to the numbers in the Random.Range method. That will give random floats instead of integers. Lets look what kind of output this will give us.

Syntax

This little example will find numbers in the same range. Remember when using integers you have to add 1 to the max numbers. That is the most important difference when using a random range in Unity.

using UnityEngine;

public class RandomNumber : MonoBehaviour
{
    void Start()
    {
        float a = Random.Range(0f, 10f);
        int b = Random.Range(0, 11);
    }
}

This is how Unity random numbers work using the random range method. Check out the official Random.Range documentation.

Check out more unity relate articles.