Whenever I try to get a different number, it gives me the same number
local mat = math.random(1,10)
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:
math.randomseed(os.clock())
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?
example
local cd = script.Parent
cd.MouseClick:Connect(function()
local int = math.random(1, 10) -- randomizes every time the click detector is used
print(int) --> should print a random number (may repeat sometime)
end)
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.
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()
repeat
mat = math.random(1,10)
if mat == oldmat then
local mat = math.random(1,10)
end
until mat ~= oldmat
print(mat)
oldmat = mat
end
script.Parent.MouseClick:Connect(function()
randomNumberGenerate()
end)
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.