Creating a random player selector

Can somebody please correct this / point out any errors?

local player = game:GetService("Players"):GetPlayers()

while true do
	wait(1)
	print(#player)
	print(player[math.random(1, #player)])
end

you can create a variable for it like so :

local players = game:GetService("Players"):GetPlayers()
local RandomPlayer = players[math.random(1,#players)]
print(RandomPlayer.Name)

creating a variable will store that value forever. Chances are when you declare

local player = game:GetService("Players"):GetPlayers()

There are not players in the server. instead you should update your variable every loop through.

local Players = game:GetService("Players")

while task.wait(1) do
    local all_players = Players:GetPlayers() -- gets current players every loop
    print(#all_players)
    print(all_players[math.random(1, #all_players)])
end
1 Like