Chosen player not functioning

This is a ServerScript inside ServerScriptService. When I test the game alone, it works fine. But when I test with two accounts, sometimes it selects one account as the killer (meaning the chosen player works) but gives the killer skin to the other player (meaning the char bit does not work properly).

I have a high suspicion it’s because of something to do with the type of loop like it already starting and defining everything before the other player joins.

When I change:

while wait(5) do

to:

while true do

It prints this error:

ServerScriptService.RolePickerScript:5: invalid argument #2 to ‘random’ (interval is empty)

while wait(5) do
	local plrs = game.Players
	
	local survivors = {}
	local chosen = plrs:GetChildren()[math.random(1, #plrs:GetChildren())]	
	game.Workspace.NoobName.Value = chosen.Name
	local char = game.Workspace:FindFirstChild(chosen.Name)
	print(char) -- this prints correctly
	local chosen = plrs:GetChildren()[math.random(1, #plrs:GetChildren())]	
	chosen.PlayerGui.Picker.Background.RoleGiven.Text = "Noob"
	chosen.PlayerGui.Picker.Background.RoleGiven.TextColor3 = Color3.fromRGB(0, 170, 255)			
	chosen.PlayerGui.Picker.Background.Visible = true

	noobify()
	armKiller() -- these functions work just not for the right player, they are both
                -- set to char which is the character of the chosen player.

	for i, plr in pairs(plrs:GetChildren()) do
		if plr ~= chosen then
			table.insert(survivors, plr)
			plr.PlayerGui.Picker.Background.RoleGiven.Text = "Survivor"
			plr.PlayerGui.Picker.Background.RoleGiven.TextColor3 = Color3.fromRGB(255, 255, 255)
			plr.PlayerGui.Picker.Background.Visible = true
		end	
	end	
	game.ReplicatedStorage.PickNoob:FireAllClients(chosen)
end

One thing I see that may be the problem here is that you have two chosen variables in your script. One sets a value in workspace which is what I assume you are using for your functions to dress the chosen player. Then, you redefine chosen which can result in two players being chosen sometimes (as its random). To fix this just define chosen once:

That means this line can be removed.

As for this, this happens because there are no players to choose in your server (the loop starts before your players joins). This can be fixed by checking if there are any players or not at the start of your loop (right below the while wait() do part):

local plrs = game.Players
if #plrs:GetChildren() == 0 then
	return
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.