How would I choose a random player from a script

  1. I am trying to use math.random to choose a random player.?

  2. I need to choose a random player from a script, but since I am not good at scripting, I don’t really know how I would do it.

  3. I have tried math.random but it gives me an error that says “Workspace.Dummy.Script:4: invalid argument #2 to ‘random’ (interval is empty)” for some reason they are taking math as something in the player.

local humanoid = script.Parent.Humanoid
local Players = game:GetService("Players")
local playerr = Players:GetChildren()
local playerRandom = math.random(1,#playerr)
print(playerRandom)

try using this one :

local humanoid = script.Parent.Humanoid
local Players = game:GetService("Players")
local playerr = Players:GetPlayers()
local playerRandom = math.random(1,#playerr)
local ChoosenPlayer = playerr[playerRandom]
print(ChoosenPlayer.Name)
1 Like

Workspace.Dummy.Script:4: invalid argument #2 to ‘random’ (interval is empty)
it gives the same error unfortunately.

I think i know whats happening

this right here is erroring because sometime there can be only 1 player and thus the program is doing math.random(1,1) which will error as it cant choose any so try puttin an or like this

local humanoid = script.Parent.Humanoid
local Players = game:GetService("Players")
local playerr = Players:GetPlayers()
local playerRandom = math.random(1,#playerr) or 1
local ChoosenPlayer = playerr[playerRandom]
print(ChoosenPlayer.Name)
1 Like

Try this:

local players = game.Players:GetPlayers()
local randomint = math.random(1, #players)
print(players[randomint])
local players = game:GetService('Players')

function getTroller()
  math.randomseed(tick())
  local playerlist = players:GetPlayers()
  if (#playerlist < 1) then return print('no player :flushed:') end
  return playerlist[math.random(1, #playerlist)]
end
2 Likes

I think this works. Since I am alone in game it give’s no player. So as long as I am alone it will print that right?

i dont use math.random too much well

1 Like
local players = {}
local service = game:GetService("Players")



game.Players.PlayerAdded:Connect(function(plyr)
	table.insert(players,plyr)
end)


game.Players.PlayerRemoving:Connect(function(plyr)
	local removingplyr = table.find(players,plyr)
	
	if removingplyr then
		table.remove(players,removingplyr)
	end
end)


local function randplayer()
	local rand = math.random(1,#players)
	for i,v in ipairs(service:GetPlayers()) do
		if i == rand then
			return v
		end
	end
end



wait(20)
local randplayer = randplayer()
print(randplayer.Name)
1 Like