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 5 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?

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

1 answer

Log in to vote
2
Answered by 5 years ago
Edited 5 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().

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

EDIT:

1local rand = Random.new(tick()) -- tick makes the seed different with every game launch
2local Power= {"Earth", "Fire", "Lightning", "Water"}
3Player.Power.Element1.Value = Power[rand:NextInteger(1, #Power)]
4 
5repeat -- Prevent the second value from being the same
6    Player.Power.Element2.Value = Power[rand:NextInteger(1, #Power)]
7until 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 — 5y
0
There is a small chance, just by random chance. You can implement safeguards against this easily however. RunKittenzRComin 170 — 5y
0
Editted to show this process. RunKittenzRComin 170 — 5y
0
Aight Thx. Kallisus 43 — 5y
View all comments (2 more)
0
Or math.randomseed Ziffixture 6913 — 5y
0
It's generally better practice to use Random.new(). RunKittenzRComin 170 — 5y
Ad

Answer this question