This article will explain the usage of the function, math.random(). It can be used to find many different "random" numbers and help randomize things in your scripting.
What Is The Random Function?
The random function takes two numbers as arguments. The numbers you put in will be rounded to the nearest integer if it is a float. (To understand these terms see, scripting terms). Here is an example of generating a random integer using math.random.
local num = math.random(1,3) print(num) --> 3 yes
In this case, I used the variable "num" to hold a random value. The random value happened to be three. Since I gave math.random() the integers 1 and 3, it generated a number from 1-3. Lets make it a little more interesting! Lets make it print something specific if the number is 1, 2, or 3.
local num = math.random(1,3) if num == 1 then print("Hello") elseif num == 2 then print("Hi there") elseif num == 3 then print("Good day") end --> Hi there
This script will print a certain greeting depending on the number. This would be good for a minigame, or something like that. Using math.random(), it will generate a number. But, for the format, you may put a local by math.random(5,10). The number 5 will represent the lowest number generated, and the number 10 will represent the highest number generated. Using this is very important for games that choose it's own choices. Here's how we can use the math.random in a brick to change it's color.
INPUT
local num = math.random(5,10)
if num = 5 then
script.Parent.BrickColor = BrickColor.new("Bright red")
if num = 6 then
script.Parent.BrickColor = BrickColor.new("New Yeller")
if num = 7 then
script.Parent.BrickColor = BrickColor.new("Cyan")
if num = 8 then
script.Parent.BrickColor = BrickColor.new("Really red")
if num = 9 then
script.Parent.BrickColor = BrickColor.new("Camo")
if num = 10 then
script.Parent.BrickColor = BrickColor.new("Navy blue")
OUTPUT:
If number was 5, then brick color will turn into "Bright red."
If number was 6, then brick color will turn into "New Yeller."
If number was 7, then brick color will turn into "Cyan."
If number was 8, then brick color will turn into "Really red."
If number was 9, then brick color will turn into "Camo."
If number was 10, then brick color will turn into "Navy blue."
-----------------------------------------------------------------------------------------------------------------------------------
The math.random function is not required to be a local variable. It may be in a script that wouldn't require any local variables. To do this, replace your variable into math.random(low,high). Here is one example, which adds a number between 5 to 10 to another value:
game.Workspace.Value.Value = game.Workspace.Value.Value + math.random(5,10)
To learn more about math.random, there may be a more complex example right here. -->[1]