How to select a random player?

I tried to make a script that selects a random player to be murderer and sheriff but it keeps saying
" ServerScriptService.GameManager:30: invalid argument #3 (string expected, got Instance)"

local function startGame()
	local selected = {}
	for i,v in pairs(Players:GetChildren()) do
		table.insert(selected,1,v)
	end

	local murderer = selected[math.random(1,#selected)]
	ReplicatedStorage.Players:WaitForChild("Murderer").Value = murderer
	print(murderer.." Is The Murderer!")
	
	table.remove(selected,getPositionOfPlayer(selected,murderer))

	local sheriff = selected[math.random(1,#selected)]
	ReplicatedStorage.Players:WaitForChild("Sheriff").Value = sheriff
	print(sheriff.." Is The Sheriff!")
	
	table.remove(selected,getPositionOfPlayer(selected,sheriff))
end
1 Like

First of all using table.insert() in this case is completely useless and not optimal.

Now, assuming this is a StringValue, you’re trying to set its value to an Instance which is the selected player. Instead use its Name (player.Name).

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local Seed = Random.new()

local RSPlayers = ReplicatedStorage.Players

local function startGame()
	local PlayersTable = Players:GetPlayers()

	local murderer = PlayersTable[Seed:NextInteger(1,#PlayersTable)]
	RSPlayers:WaitForChild("Murderer").Value = murderer.Name
	print(murderer.." Is The Murderer!")

	table.remove(PlayersTable, table.find(PlayersTable, murderer))

	local sheriff = PlayersTable[Seed:NextInteger(1,#PlayersTable)]
	RSPlayers:WaitForChild("Sheriff").Value = sheriff.Name
	print(sheriff.." Is The Sheriff!")

	table.remove(PlayersTable, table.find(PlayersTable, sheriff))
end
2 Likes