You're listening for game.Players.PlayerAdded
, which is an event that fires when a player joins. This isn't quite what you want, but it's great that you tried to solve this problem yourself before asking.
We can use the Player.Team
rather than the Player.TeamColor
property to make our code clearer.
We need two scripts. One, server-side, should handle requests from the client (player's computer) to change teams. It should check if the team requested is one that can be switched to, and if so, switch the player's team. The client-side code should listen for button presses and fire the server when pressed.
Server-side Script
code in game.ServerScriptService
:
01 | local TeamsService = game:GetService( "Teams" ) |
03 | local TeamSwitch = game.ReplicatedStorage.Network.TeamSwitch |
05 | TeamSwitch.OnServerEvent:Connect( function (Player, Team) |
06 | if typeof(Team) ~ = "instance" then |
10 | if not Team:IsA( "Team" ) or Team.Parent ~ = TeamsService then |
Client-side LocalScript
code in the GUI button (I recommend moving this to game.StarterPlayer.StarterPlayerScripts
, as scripts really don't belong in GUI objects):
01 | local TeamsService = game:GetService( "Teams" ) |
03 | local LocalPlayer = game.Players.LocalPlayer |
05 | local TeamSwitch = game.ReplicatedStorage.Network.TeamSwitch |
07 | local Button = script.Parent |
09 | Button.MouseButton 1 Click:Connect( function () |
10 | local TeamSwitchTarget = nil |
12 | if LocalPlayer.Team = = TeamsService.Red then |
13 | TeamSwitchTarget = TeamsService.Blue |
15 | TeamSwitchTarget = TeamsService.Red |
18 | TeamSwitch:FireServer(TeamSwitchTarget) |
Note that Network
is a folder, and TeamSwitch
is a RemoteEvent
.