How would I make a script that changes a player's team when they die?

As the title implies, I’m trying to make a script that will put you on a spectating team on the sidelines when you die, but don’t know how.

3 Likes

First, you’ll need to define the player, and then that player’s character. Then you’d do something like the below code once you’re ready for the player to be set to the spectating team after dying.

local spectateTeam = teams['Spectators'] -- name this whatever ur team name is

local player
local character -- let me know if u need help w/ these

character.Humanoid.Died:Connect(function() -- event that connects when the humanoid dies
   player.Team = spectateTeam
end)
1 Like

How do I define the player and character? Sorry, I haven’t done much of this kind of stuff before

No problem.

To define the character you could do a lot of different things, but I’ll give you two examples. It depends on when you want to connect the events.

In this example, I define the player and their character as soon as they join the game.

local pl = game:GetService('Players')
local teams = game:GetService('Teams')
local spectateTeam = teams['Spectators'] -- name this whatever ur team name is

pl.PlayerAdded:Connect(function(player) -- event when player first joins the game

   local character = player.Character or player.CharacterAdded:Wait() -- only defines the character once, so this code will only happen once
   character.Humanoid.Died:Connect(function() -- event that connects when the humanoid dies
      player.Team = spectateTeam
   end)

end)

In the below example, I grab a list of all the players in the game & then use the same code with all their characters.

local pl = game:GetService('Players')
local teams = game:GetService('Teams')
local spectateTeam = teams['Spectators'] -- name this whatever ur team name is

for _,player in pairs(pl:GetPlayers()) do -- for loop that cycles thru the current playerlist and connects an event to all of their characters
   if player.Team ~= spectateTeam then
      local char = player.Character or player.CharacterAdded:Wait()
      character.Humanoid.Died:Connect(function() -- event that connects when the humanoid dies
         player.Team = spectateTeam
      end)
   end
end
1 Like

This worked for me in singleplayer testing. I will test this with multiple accounts and see if it works out

1 Like

Update: It works! Thank you so much for helping me out with this!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.