Random role for each player

i need to randomize role for each player, every round. roles cannot repeat. after some loops output says that random interval is empty. hwo di i fix this?

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

local roles = {
	"one",
	"two",
	"three",
	"four"
}

local availablePlayers = Players:GetPlayers()
local availableRoles = roles

local function onGameStart(value)
	if value == "InProgress" then
		repeat
			local selectedRole = math.random(1, #availableRoles)
			local selectedPlayer = math.random(1, #availablePlayers)
			table.remove(availableRoles, selectedRole)
			table.remove(availablePlayers, selectedPlayer)
			print(roles[selectedRole], Players:GetPlayers()[selectedPlayer])
			wait()
		until #availableRoles == 0
	end
end

local function onGameEnd(value)
	if value ~= "InProgress" then
		availablePlayers = Players:GetPlayers()
		availableRoles = roles
		for i, v in pairs(Players:GetPlayers()) do
			v.Character.HumanoidRootPart.CFrame = game.Workspace.Lobby.SpawnLocation.CFrame
		end
	end
end

ReplicatedStorage.GameState.Changed:Connect(onGameStart)
ReplicatedStorage.GameState.Changed:Connect(onGameEnd)
1 Like

availablePlayers is eventually going to be empty as you are getting it out of the function, and availableRoles isn’t a clone of roles, just a variable for it, to fix this, just put them in the onGameStart function

1 Like

should i put both availablePlayers and availableRoles in the function?

edit: also check roles table with

for i, v in pairs(roles) do
	print(v)
end

and it one role gets removed from it every round

Yes, as you said after a few rounds it says the interval is empty, put availablePlayers and roles in the function

interval no longer goes empty but sometimes my character gets nil role
image

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

local function onGameStart(value)
	if value == "InProgress" then
		local roles = {
			"one",
			"two",
			"three",
			"four"
		}
		local availablePlayers = Players:GetPlayers()
		local availableRoles = roles
		repeat
			local selectedRole = math.random(1, #availableRoles)
			local selectedPlayer = math.random(1, #availablePlayers)
			table.remove(availableRoles, selectedRole)
			table.remove(availablePlayers, selectedPlayer)
			print(availableRoles[selectedRole], Players:GetPlayers()[selectedPlayer])
			wait()
		until #availableRoles == 0
	end
end

local function onGameEnd(value)
	if value ~= "InProgress" then
		for i, v in pairs(Players:GetPlayers()) do
			v.Character.HumanoidRootPart.CFrame = game.Workspace.Lobby.SpawnLocation.CFrame
		end
	end
end

ReplicatedStorage.GameState.Changed:Connect(onGameStart)
ReplicatedStorage.GameState.Changed:Connect(onGameEnd)
1 Like

It’s just printing nil because you do table.remove before the print

2 Likes

so every seems to be working. thanks a lot

1 Like