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

Why math.random is unreal random?

Asked by 7 years ago
local pathpart = workspace.IslandParts.islandpaths.islandpath

for i,pathpart in pairs(pathpart.Parent:GetChildren()) do

    if pathpart.Name == "islandpath" then

        local palmgen= math.random(30)
        if palmgen == 2  then
            print("PALM GEN IS: ",palmgen)
            local palm = game.ReplicatedStorage.Assets.islandnature.palm:Clone()
            palm.Parent = workspace
            palm:MoveTo(pathpart.Position)

        else
            print("PLAM GEN IS: ",palmgen)
        end
    end

end

Facilities should create a random object if palmgen = 2, but math.random ALWAYS produces the same random numbers. How to make this feature really random?

1
math.random uses a seed to calculate its 'random' output. In studio, the seed doesn't update when you test it again and again. It will be different in an actual game, though. OldPalHappy 1477 — 7y

1 answer

Log in to vote
2
Answered by 7 years ago

You need to warm the pseudo random generator by using math.randomseed(x). Where x is the seed for the generator. One of the most common ways for warming it up is to use tick() as the input. Applying this to your script would make it into.

local pathpart = workspace.IslandParts.islandpaths.islandpath
math.randomseed(tick())

for i,pathpart in pairs(pathpart.Parent:GetChildren()) do

    if pathpart.Name == "islandpath" then

        local palmgen= math.random(30)
        if palmgen == 2  then
            print("PALM GEN IS: ",palmgen)
            local palm = game.ReplicatedStorage.Assets.islandnature.palm:Clone()
            palm.Parent = workspace
            palm:MoveTo(pathpart.Position)

        else
            print("PLAM GEN IS: ",palmgen)
        end
    end

end

1
Important fact about randomseed: you only ever want to use it once or 0 times. Setting it too often can result in extremely biased results, as it 'reboots' the RNG algorithm, which is only non-biased over a long period of time. adark 5487 — 7y
Ad

Answer this question