Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does my random player select not work?

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

✓ Accepted answer

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!

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

This discussion is preserved as it was. New answers, comments, and votes are closed.