math.Random returns the same value

I made a game with difficulties and 1 is hard, 2 is medium, 3 is hard. I used math.Random(1, 3) but it almost always return the same value. What is the problem?

Are you pressing play and seeing that it’s the same value? math.random is seeded by gametime, you can give it a new seed e.g.:

local RNG = Random.new(seed_number) --> Random.new() is pretty well seeded though, I'd just leave it as Random.new() instead of giving it a number

local value = RNG:NextInteger(1, 3)
print(value) 

or

math.randomseed(seed_number)
1 Like

Are you using math.randomseed?

“almost always”, it might just be chance if it’s not always returning the same value.

no
(30 Character)…

Math.random requires math.randomseed to function. Use Random.new to avoid this mess entirely.

Most people do math.randomseed(tick()) to get a nice random number each time. Without randomseed, you will get the same number every time. (Important to note that the seed should constantly change)

That’s not necessarily true, it will still be random - but not if it’s starting at the same point e.g. if you’ve just pressed play

My results from:

for i = 1, 10 do
    print(math.random(1, 3))
end

were

3
2
3
3
3
1
2
3
1
2

I meant for maximum randomness. I assume he wants it to not really be predictable and as you know computers are terrible at random numbers. The Random.new is much more random (although still not the greatest) even without a seed.

1 Like

Well there is a 1/3 chance to get that number, This is the RNG work.

math.random was edited by Roblox to use a Random object under the hood. They are practically the same now. Just the seed was likely needed.

2 Likes

There is a way to use the math.Random that is if you want easy mode to be the most common, medium mode to be medium common and hard to be rare then you can make a math.random that goes to a high number and then do something like this

local RNG = math.random(0, 100)
if RNG <= 50 then
easy
elseif RNG <= 80 then
medium
else
hard
end

1 Like

I found another way to do this. If the value is same, It will repeat this. If not, It will continue.

1 Like

This was not what I was looking for but it looks cool

1 Like