✓ Accepted answer
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:
local TeamsService = game:GetService("Teams")
local TeamSwitch = game.ReplicatedStorage.Network.TeamSwitch
TeamSwitch.OnServerEvent:Connect(function(Player, Team)
if typeof(Team) ~= "instance" then
return
end
if not Team:IsA("Team") or Team.Parent ~= TeamsService then
return
end
Player.Team = Team
end)
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):
local TeamsService = game:GetService("Teams")
local LocalPlayer = game.Players.LocalPlayer
local TeamSwitch = game.ReplicatedStorage.Network.TeamSwitch
local Button = script.Parent
Button.MouseButton1Click:Connect(function()
local TeamSwitchTarget = nil
if LocalPlayer.Team == TeamsService.Red then
TeamSwitchTarget = TeamsService.Blue
else
TeamSwitchTarget = TeamsService.Red
end
TeamSwitch:FireServer(TeamSwitchTarget)
end)
Note that Network is a folder, and TeamSwitch is a RemoteEvent.
1 comment
I want the player to switch teams when they press the textbutton from neutral to the other team