How To Choose A Random Player In The Game?

This is a support category for asking questions about how to get something done on the Roblox websites or how to do something on Roblox applications such as Roblox Studio.

You can write your topic however you want, but you need to answer these questions:

  1. I want to create a system to choose a random player when there are at least 2 players in the game.

  2. My issue is the script doesnt choose a random player and errors multiple times.

  3. I’ve checked Youtube videos but most code outdated I checked the forum couldn’t find much on this particular topic.

So this is my script that is giving me difficulties if it is an easy fix if you could tell me why it was messed up I would appreciate it.

for _, plr in ipairs(game.Players:GetPlayers()) do
	if #plr >= 2 then
		local RandomPlayer = plr:GetChildren()[math.random(1,#plr)]

You gotta first get a random number from 1 to the number of players there is like
local rn = math.random(1, #game.Players:GetPlayers())

Then you iterate through the player list and check if i equals your random number

for i, player in pairs(game.Players:GetPlayers()) do
if i == rn then

if #plr >= 2 then should be checking the number of children of the player object, not the player object itself: Use the plr:GetChildren() instead.

for _, plr in ipairs(game.Players:GetPlayers()) do
local children = plr:GetChildren()
if #children >= 2 then
local randomPlayer = children[math.random(1,#children)]

local players = game.Players:GetChildren()

local function selectrandomplayer()
if #players >= 2 then
return players[math.random(1,#players)

Wrote it on mobile so pls fix typos

I forgot to mention wrong category belongs in #help-and-feedback:scripting-support

you probably dont need the ipairs part, maybe thats the reason why?
you can use this:

if #game.Players:GetPlayers() >= 2 then
local RandomPlayer = game.Players:GetPlayers()[math.random(1,#game.Players:GetPlayers())]

I didn’t try it out so tell me if anything bad happens

It doesnt work it says ServerScriptService.Script:2: invalid argument #2 to ‘random’ (interval is empty)

1 Like

You wouldn’t need a for loop for this. You could do something like:

local players = game:GetService("Players")
local randomPlayer = players[math.random(1,#players)]

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