function getTeams() local teamNumber = 1 repeat wait() local lobby = {} local teams = {"Red", "Blue"} for _, player in pairs(game.Players:GetPlayers()) do if player.TeamColor == game.Teams["Lobby"].TeamColor then local character = player.Character if character and character:FindFirstChild("Torso") then table.insert(lobby, player) end end end local randomPlayer = lobby[math.random(1, #lobby)]-- Error here (Line 77) randomPlayer.TeamColor = game.Teams[teams[teamNumber]].TeamColor toMap(randomPlayer) local lobbyNumber = 0 for _, player in pairs(game.Players:GetChildren()) do if player.TeamColor == game.Teams["Lobby"].TeamColor then if player.Character:FindFirstChild("Torso") then lobbyNumber = lobbyNumber + 1 end end end teamNumber = teamNumber == 1 and 2 or 1 until lobbyNumber == 0 end
ServerScriptService.GameScript:77: bad argument #2 to 'random' (interval is empty)
The code here is suppose to get all the players in a game and give them all random teams and keeping it even. It also is suppose to give a team to any new player who may join late, but still keep the teams even. For some reason it is error at local randomPlayer = lobby[math.random(1, #lobby)]
and idk why. It seems to work if you have say 4 players in the game and the starts, but if another play joins mid game the output has that error. How can I get it to just add the player to the game?
Since a new server starts before a client(the player) joins, we need to wait until a new player join. Also, I think some parts of your script are unnecessary.
local CurrentTeam = 'Red' local lobby = {} game.Players.PlayerAdded:Connect(function(plr) table.insert(lobby, plr) --I'm not really good with teams, so just do whatever you do to turn this player's team color to the color of CurrentTeam if CurrentTeam == 'Red' then CurrentTeam = 'Blue' else CurrentTeam = 'Red' end end) game.Players.PlayerRemoving:Connect(function(plr) --You know, what if a player decides to leave? for i, v in pairs(lobby) do if v == plr then table.remove(lobby, i) if CurrentTeam == 'Red' then --so the even team thing does not mess up CurrentTeam = 'Blue' else CurrentTeam = 'Red' end return end end warn('Oh no! We could not remove a player from the lobby table!') --Runs if it never finds the player. end)