Hello, I'm trying to make a team balance script, the problem is that it's not assigning anything right. No errors at all.
This is a server-sided script placed in ServerScriptService and fires the function when a player is leaving or joining.
I tried print debugging and only the commented block worked when I tried with two players, I am not looking for a corrected version of the script, I just need to know why it is not working. Thanks for viewing this!
local Players = game:GetService("Players") local function balanceTeams(player) local tableOfPlayers = Players:GetPlayers() local numOfPlayers = #tableOfPlayers if not numOfPlayers == 1 then for i,v in pairs(tableOfPlayers) do if i <= math.ceil(numOfPlayers / 2) and not v.Team == game.Teams.Survivors then v.Team = game.Teams.Survivors else break end end for i,v in pairs(tableOfPlayers) do if not v.Team == game.Teams.Survivors then v.Team = game.Teams.Zombies end end elseif numOfPlayers == 1 then --only part that worked with two players. tableOfPlayers[1].Team = game.Teams.Zombies end end Players.PlayerAdded:Connect(balanceTeams) Players.PlayerRemoving:Connect(balanceTeams)
So I solved my own problem, here is the code, I just tested and played around with the script and it worked. You can take this and study it but make sure there are two teams named "Survivors" and "Zombies"
--Variables/Tables local Players = game:GetService("Players") --Functions local function balanceTeams(player) local tableOfPlayers = Players:GetPlayers() local numOfPlayers = #tableOfPlayers if numOfPlayers > 1 then for i,v in pairs(tableOfPlayers) do if i <= math.ceil(numOfPlayers / 2) and not v.Team == game.Teams.Survivors then v.Team = game.Teams.Survivors print(2) else break end end for i,v in pairs(tableOfPlayers) do if not v.Team == game.Teams.Survivors then v.Team = game.Teams.Zombies print(3) end end elseif numOfPlayers == 1 then print(1) tableOfPlayers[1].Team = game.Teams.Zombies end end --Events Players.PlayerAdded:Connect(balanceTeams) Players.PlayerRemoving:Connect(balanceTeams)