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

Math.random how to make it not pick the same string?

Asked by 4 years ago

i'm trying to make it get a random string but sometimes they both pick the same string how can I prevent that?

    local Power= {"Earth", "Fire", "Lightning", "Water"}
    Player.Power.Element1.Value = Power[math.random(1, #Power)]
    Player.Power.Element2.Value = Power[math.random(1, #Power)]

1 answer

Log in to vote
2
Answered by 4 years ago
Edited 4 years ago

Every math.random without a seed uses the same seed, and this creates the same result. To fix this, you can use Random.new().

local rand = Random.new(tick()) -- tick makes the seed different with every game launch
local Power= {"Earth", "Fire", "Lightning", "Water"}
Player.Power.Element1.Value = Power[rand:NextInteger(1, #Power)]
Player.Power.Element2.Value = Power[rand:NextInteger(1, #Power)]

EDIT:

local rand = Random.new(tick()) -- tick makes the seed different with every game launch
local Power= {"Earth", "Fire", "Lightning", "Water"}
Player.Power.Element1.Value = Power[rand:NextInteger(1, #Power)]

repeat -- Prevent the second value from being the same
    Player.Power.Element2.Value = Power[rand:NextInteger(1, #Power)]
until Player.Power.Element2.Value ~= Player.Power.Element1.Value

If there are any errors, please comment.

1
is there a chance that it'll pick the same string? Kallisus 43 — 4y
0
There is a small chance, just by random chance. You can implement safeguards against this easily however. RunKittenzRComin 170 — 4y
0
Editted to show this process. RunKittenzRComin 170 — 4y
0
Aight Thx. Kallisus 43 — 4y
View all comments (2 more)
0
Or math.randomseed Ziffixture 6913 — 4y
0
It's generally better practice to use Random.new(). RunKittenzRComin 170 — 4y
Ad

Answer this question