How to get random players?

hi, I’m trying to select random players from players based on how many I want to select (for example 0 or 10 players) but this only selects one each time.

local plrs = game.Players:GetPlayers()
local  randomplrs = 5 --random players
local  randomplayers = plrs[math.random(randomplrs, #plrs)]
for i, plr in pairs(plrs) do print(i)
	if plr == randomplayers then	
		print("1+ random player")
	end

thank you in advance for any help

2 Likes
local Players = game:GetService("Players")
local allPlayers = Players:GetChildren()
local randPlayer = allPlayers[math.random(1, #allPlayers+1)]

That should do it.

1 Like
local plrs = game:GetService("Players"):GetPlayers()
local randomplrs = 5
local randomplayers = {}

for i=1, randomplrs do
	local rnd = math.random(1, #plrs)
	randomplayers[i] = plrs[rnd]
	table.remove(plrs, rnd)
end

print("Selected Random Players:", randomplayers )
local Game = game
local Players = Game:GetService("Players")
local RandomObject = Random.new()

local function GetNPlayers(N)
	local PlayersArray = Players:GetPlayers()
	local RandomPlayers = {}
	for I = 1, N do
		if #PlayersArray == 0 then break end
		table.insert(RandomPlayers, table.remove(PlayersArray, RandomObject:NextInteger(1, #PlayersArray)))
	end 
	return RandomPlayers
end
3 Likes

Most answers here use table.remove which will do operations with a big part of the table. A good way of optimizing this is using a faster function, which just removes the value and swaps it with the last one:

local function replace(t, i)
    local length = #t
    t[i] = t[length]
    t[length] = nil
    return t
end

After that you can use @Forummer’s answer and replace table.remove with replace.

Or you can try this strange (and faster?) way of doing it with bitwise operations:

local plrsserv = game:GetService("Players")
local plrs = plrsserv:GetPlayers()

local nplrs = #plrs 

local choosenplrs = {}
local choosenum = math.random(bit32.lshift(1, nplrs - 1), bit32.lshift(1, nplrs) - 1)

for i = 1, nplrs do
    local n = bit32.band(choosenum, bit32.lshift(1, i - 1))
    if n then table.insert(choosenplrs, plrs[i]) end
end

I apologize for the inactivity, wouldn’t it be possible without the table?
probably not, never mind. Thanks for the help everyone. :+1:

1 Like

You forgot one end.

local plrs = game.Players:GetPlayers()
local  randomplrs = 5 --random players
local  randomplayers = plrs[math.random(randomplrs, #plrs)]
for i, plr in pairs(plrs) do print(i)
	if plr == randomplayers then	
		print("1+ random player")
	end
end
1 Like

oh, but I just forgot to copy that, I have it right in my original script