Math.random outputs repeated

Whenever I try to get a different number, it gives me the same number

local mat = math.random(1,10)

I’m pretty sure when the script runs when you play the game, the variable is set to a random number (from the range you put) and when you use that variable anytime it will always be the same number that was selected. Someone please correct me if I’m wrong.

The script is in a click detector script.

Oh, sorry. Can you show the whole script?

You could add this to the top of your script:


Wait, what does your script look like? Do you get a new value whenever the ClickDetector is used? Or do you just use the same variable?


local cd = script.Parent

  local int = math.random(1, 10) -- randomizes every time the click detector is used
  print(int) --> should print a random number (may repeat sometime)

Just to add onto @HugeCoolboy2007’s post,

To understand it better, you can use this for quick demonstration

When using math.random on the compiler, you will notice it will always give you the same result unless you set a seed.

1 Like

If I want to prevent it from duplicating, I will just detect if it’s the same, if it is then It will run the function again and it repeats until the mat is not the same as the oldmat.

local oldmat = 0
local mat

function randomNumberGenerate()
		mat = math.random(1,10)

		if mat == oldmat then
			local mat = math.random(1,10)

	until mat ~= oldmat
	oldmat = mat


Edit1: I realized the script has a bug, fixing it rn.
Edit2: Code Fixed.
Edit3: Making the code run by a clickdetector and fixed numbers generating twice if the number is the same.