How do I make it so math.random doesn’t have the same value twice?

So, I’m trying to a dialog script where a random player is picked to be speaking. But the problem is, sometimes the same person can be picked twice to speak. Leading to problems like “user1: I like cheese” “user1 (again): no! I disagree!”
Unless you’re playing solo, this can be a problem.
How do I fix this?


local function getRandomPlayer()
    local players = game.Players:getPlayers()
    local number = math.random(1,#players)
    local randomPlayer = players[number]
    randomPlayerName = randomPlayer.Name
    randomPlayerId = randomPlayer.UserId
    game.Workspace.Values.CurrentSpeaker.Value = randomPlayerName
end

—This is the how getRandomPlayer() works v

local function intro()
    local NPC_Image = "http://www.roblox.com/asset/?id=13916757036"
    CreateDialogueEvent1:FireAllClients(NPC_Image,"Welcome, children, To the best forest camp you will ever have in your life!")
    game.Workspace.Values.CurrentSpeaker.Value = "Guide"
    wait(9)
    getRandomPlayer()
    CreateDialogueEvent1:FireAllClients(getPlayerImage(randomPlayerId), "This is gonna be the best day ever!")
    game.Workspace.Values.CurrentSpeaker.Value = randomPlayerName
    wait(5)
    getRandomPlayer()
    CreateDialogueEvent1:FireAllClients(getPlayerImage(randomPlayerId), "I know right!? I love camping!")
    game.Workspace.Values.CurrentSpeaker.Value = randomPlayerName
    wait(7)
    local NPC_Image = "http://www.roblox.com/asset/?id=13916757036"
    CreateDialogueEvent1:FireAllClients(NPC_Image,"Feel free to explore the campus!")
    game.Workspace.Values.CurrentSpeaker.Value = "Guide"
    wait(50)
    game.ReplicatedStorage.TransitionEvent:FireAllClients()
end

``

You can put

math.randomseed(tick())

at the top of the script, or just use

Random.new:NextInteger(minNumber, maxNumber)

I’ve annotated the code below and made a couple of edits.
I’ve also assumed you are not using the code anywhere else.

local function getRandomPlayer()
    local lastSpeaker = game.Workspace.Values.CurrentSpeaker.Value  --Get the previous value
    local players = game.Players:getPlayers()
    local number = math.random(1,#players)
    local randomPlayer = players[number]
    randomPlayerName = randomPlayer.Name
--Compare the new value to the previous
    if randomPlayerName ~= lastSpeaker or #players == 1 then  --If not the same (or there is only 1 player!) then carry on as normal
        randomPlayerId = randomPlayer.UserId
        game.Workspace.Values.CurrentSpeaker.Value = randomPlayerName
    else  --Is the same, so try function again.
        getRandomPlayer()
    end
end
1 Like

Don’t forget that math.random will error, if min and max are the same value:

local number = if #players == 1 then 1 else math.random(1,#players)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.