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

Why does my random player select not work?

Asked by
Dexiber 272 Moderation Voter
3 years ago

i am trying to make a random player select for my murder mystery game.

But once it tries to do the math.random(1,#v) - v is for players:GetChildren(), the output gives me an error that says "attempt to get length of an instance value"

here is my script:

for _, v in pairs(game.Players:GetChildren()) do
        local randomSelect = math.random(1,#v)
        if v ~= v[randomSelect] then
            revealRoleRemote:FireClient(v,"Normal")
        else
            revealRoleRemote:FireClient(v,"Murder")
            end
        end

Please help me out!

2 answers

Log in to vote
1
Answered by 3 years ago

It's because you are looping through the list of players making v the actual player object.

You should get the list of players and access the table with a random number:

local players = game.Players:GetPlayers() -- list of players

local randomPlayer = players[math.random(1, #players)]
--see how "players" is a list and we index with a random number
--from 1 to the list's length, giving us a random player!
Ad
Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

This should work

for _, v in pairs(game.Players:GetPlayers()) do
        local randomSelect = math.random(1,#game.Players:GetPlayers())
        if v ~= game.Players[randomSelect] then
            revealRoleRemote:FireClient(v,"Normal")
        else
            revealRoleRemote:FireClient(v,"Murder")
            end
        end

Answer this question