Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

math.random keeps picking same number?

Asked by 8 years ago

script:

script.Parent.PrimaryPart = script.Parent.BasePart

local r = math.random(1,2)

if r == 1 then
    local room = game.ReplicatedStorage.spawnconn2:Clone()
    room.Parent = game.Workspace
    room:MoveTo(script.Parent.BasePart.Position)
elseif r == 2 then
    local room = game.ReplicatedStorage.spawnconn1:Clone()
    room.Parent = game.Workspace
    room:MoveTo(script.Parent.BasePart.Position)
end


problem: this script always picks 2 as the number. Every. Single. Time. I've tested it with adding more numbers, like 3, and it seems to always pick the highest number. Example, if it was (1,10), it would always pick 10. If it was (1,4), it would always pick 4. And, in this scripts case, it always picks 2, never 1. Am I missing something? Why won't it pick randomly between the two?

*All help is appreciated! *

1 answer

Log in to vote
1
Answered by
Uglypoe 557 Donator Moderation Voter
8 years ago

Roblox is bad in many ways, we all know that. This is one of those ways. You have to call a different random event first to basically set up the script to do, well, random things. Try this:

As the first line of your script, put this line of code I was given a few weeks ago. Don't edit it at all. It should fix your math.random() issues:

math.randomseed(tick()%1*1e6)
0
Also, I have no explanation for why that line of code works. All I know is that I had this same issue weeks ago, and this was the solution somebody gave me (and it worked!). Uglypoe 557 — 8y
0
Well, Roblox uses a seed algorithm for creating random numbers as Mine Craft uses a seed to generate it's worlds. And just like Mine Craft, Roblox has a default seed. To change this, put in a different seed. tick() will always be different as tick() returns the local UNIX time, which is the number of seconds since the Unix epoch BobserLuck 367 — 8y
0
The reason it works quite well is because the modulus operator (%) is pulling the preceding decimal digits from tick(), which is incredibly precise. Then it multiplies it by the SN of 1,000,000, which moves them to their respective unit place. ScriptGuider 5640 — 6y
0
In other words, it uses the precision of tick() by converting it's nth decimal place into a whole number. ScriptGuider 5640 — 6y
Ad

Answer this question