So I’ve been developing a game recently where every 180 seconds (3 minutes) a new map generates. Well, I have come across an issue where math.random returns the same value (In my case 2).
Any ideas of what I am doing wrong?
Here is my code:
local map1 = game.ReplicatedStorage.Maps.Map1
local map2 = game.ReplicatedStorage.Maps.Map2
local map3 = game.ReplicatedStorage.Maps.Map3
local allinall = game.ReplicatedStorage.Maps.AllInAll
function clonemap1 ()
local map1clone = map1:Clone()
map1clone.Parent = game.Workspace
wait(180)
map1clone:Destroy()
end
function clonemap2 ()
local map2clone = map2:Clone()
map2clone.Parent = game.Workspace
wait(180)
map2clone:Destroy()
end
function clonemap3 ()
local map3clone = map3:Clone()
map3clone.Parent = game.Workspace
wait(180)
map3clone:Destroy()
end
function allinallclone ()
local allinallclone = allinall:Clone()
allinall.Parent = game.Workspace
wait(180)
allinallclone:Destroy()
end
while true do
local randomnum = math.random(1,4)
if randomnum == 1 then
print(randomnum)
clonemap1()
end
if randomnum == 2 then
print(randomnum)
clonemap2()
end
if randomnum == 3 then
print(randomnum)
clonemap3()
end
if randomnum == 4 then
print(randomnum)
allinallclone()
end
end
This behavior is to be expected when using random numbers. With only four options, there’s a 25% or 1/4 chance that you will get the same number as your previous number. What you’re looking for is making your random map selection a bit less random. The simplest way to do this is to roll a random number until you get something different from before.
Here is a quick example that will print 10 random numbers no repeat numbers back to back:
local lastNum = -1
local randomNum = lastNum
for i = 1, 10 do
while randomNum == lastNum do
randomNum = math.random(1, 4)
end
lastNum = randomNum
print(randomNum)
end
FWIW: I personally recommend using the Random object if you need a pseudorandom number generator. Depending on how many cases of pseudorandomisation and seeded results you need, randomseed can globally affect all cases of pseudorandom generation and that might not be desirable especially if you have a case where you also need deterministic generation.
Random will automatically pull a seed when not given any arguments so each time you create a new object it’ll have a different seeding and thus different pattern whenever you call it.
-- Create the object
local RNG = Random.new()
-- Get a new result
RNG:NextInteger(1, 4)
math.random always generates the same “random” values in the same “random” order if no random seed is passed. As @Forummer said use math.randomseed(tick())
no one have ever made a real random generator.