math.random not so random?
I'm working on a script that chooses a random number between 1 to 4 and then does something based on that value. The issue is that I get the same values in the same order very time. For example, the game will give values 4, 2, 2, 3 in that order etc... Not quite sure what I can do to solve this issue.
Here's some code to look at. I've changed some variable names and other things so as to not give away any details at this point of what I'm working on.
Code:
function Activity:ValueSelect()
self.Value = math.random(1,4)
if self.Value == 1 then
self.NextValue = stuff
self.CurrentValue = self.Variable1
elseif self.Value == 2 then
self.NextValue = stuff
self.CurrentValue = self.Variable2
elseif self.Value == 3 then
self.NextValue = stuff
self.CurrentValue = self.Variable3
elseif self.Value == 4 then
self.NextValue = stuff
self.CurrentValue = self.Variable4
end
end
EDIT: Okay now it works. Solution is to use math.randomseed()) to generate a random seed for the function to use when generating numbers. My solution is to check a timer then pop off a random number before generating a number for the function. This works reliably.
Code:
function Activity:ValueSelect()
math.randomseed(self.MissionTimer:LeftTillSimMS(8)) --we generate the seed here
math.random(); --pop off a number to ensure randomness
self.Value = math.random(1,4) --generate numbers for our function.
if self.Value == 1 then
self.NextValue = stuff
self.CurrentValue = self.Variable1
elseif self.Value == 2 then
self.NextValue = stuff
self.CurrentValue = self.Variable2
elseif self.Value == 3 then
self.NextValue = stuff
self.CurrentValue = self.Variable3
elseif self.Value == 4 then
self.NextValue = stuff
self.CurrentValue = self.Variable4
end
end