Why my Roblox script doesn't work correctly

41 Views Asked by At

I have problem with my lua script to roblox. Script has to firstly create team and add player to it. When the first player join to the game everything work correctly but if the second player join, then team will be created correctly but second player will be added to the first player's team.

local teamsFolder = game:GetService("Teams")

game.Players.PlayerAdded:Connect(function(player)
    local team = Instance.new("Team")
    team.Name = player.Name
    team.Parent = teamsFolder
    team.AutoAssignable = false
    
    player.Team = team
end)

I also tried to replace 9 line for player.Team = teamsFolder[player.Name] but it also doesn't work.

1

There are 1 best solutions below

0
user15611379 On BEST ANSWER

Each new Team needs a unique TeamColor:

local teamsFolder,tab=game:GetService("Teams"),{}

game.Players.PlayerAdded:Connect(function(player)
    local team,teamcolor=Instance.new("Team"),nil
    team.Name,team.AutoAssignable=player.Name,false
    repeat
        teamcolor=BrickColor.random()
    until not table.find(tab,teamcolor)
    table.insert(tab,teamcolor)
    team.TeamColor,team.Parent=teamcolor,teamsFolder
    player.Team=team
end)

game.Players.PlayerRemoving:Connect(function(player)
    table.remove(tab,table.find(tab,player.TeamColor))
    teamsFolder[player.Name]:Remove()
end)