Generating Random Numbers in Unity

Rusben Guzman
3 min readMay 13, 2021

--

In video games it’s very common to use random values, we could create an aleatory power up like Mario Kart or a secret price like the chest in Clash Royale. Unity provides the method Random.Range() to generate random numbers, receiving as a parameter the min and the max of the range.

If you pass parameters int values it is gonna generate a value from “min” to “max — 1” (exclusive), but if you pass float values as parameters it is gonna return a value from “min” to “max” (inclusive).

Ok but only numbers is not enough for some functionalities, so let’s go a step beyond, in this example we are gonna create a script to change the color of the player each time the space key is pressed.

  • Open the player script and create an array of Color to define the color range:
  • Then detect the space key:
  • Now we have to generate a random index to select the color from the array later:
  • To change the color, you have to use the GetComponent<Renderer>().material.color and assign a random color from the array of color that we defined before:
  • And that’s it you have a change color feature:

Random number is a very useful feature with so many applications,use it wisely and create amazing games.

--

--

Rusben Guzman

A Software Engineer passionate about game dev and interactive products with Unity. I consider video games to be the artistic expression of programming.