Checking if a team member died

Hello, I’m currently making a game and wondering how to make a script that checks if a player from a certain team died. I’ve tried some scripts and checked forums, however nothing seems to work and there are no errors in the output section either. Below is the code I tried using. Thanks in advance.

local character = script.Parent
local humanoid = character:WaitForChild("Humanoid")
local Teams = game:GetService("Teams")
local player = game.Players.LocalPlayer

game:GetService('Players').PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		character:WaitForChild("Humanoid").Died:Connect(function()
			if player.Team == Teams.Red then
				player.PlayerGui.Score.Frame.CI.Counter.Text = player.PlayerGui.Score.Frame.CI.Counter.Text + 1
			end
		end)
	end)
end)

1 Like

PlayerAdded

based on the first line this script is probably inside startercharacter, meaning the Player Added connection will only fire for other players joining after your character loads. You need to also check for existing players with a for loop as well as the connection

-- initial check
for _, otherplayer in ipairs(game:GetService("Players"):GetPlayers()) do
    loadfunction(otherplayer)
end

-- joining players check
game:GetService("Players").PlayerAdded:Connect(loadfunction)

PlayerGui/Shadowing

You cannot edit other player’s gui, if you are trying to edit the local player’s gui you need to change the variable name. Shadowing means you have two variables named the same, only one of these variables will be accessable for the function scope.

local player = game.Players.LocalPlayer

game:GetService('Players').PlayerAdded:Connect(function(player) --player is shadowed
--You cannot access line 1 player in this function anymore
    print(player.Name)
end)


game:GetService('Players').PlayerAdded:Connect(function(otherPlayer) --player is not shadowed
--Use player for the local player like you intend
    print(otherPlayer.Name)
    print(player.Name)
end)

You should rename player for game.Players.PlayerAdded:Connect(function(player) because you already defined the variable on line 4.

Since you’re writing this in a localscript, this will only connect to players that join after you joined, not players before. A solution to this would be writing a for pairs loop on game.Players first, to collect all the players, and then connecting the PlayerAdded() event.

I feel like the best solution is to keep track of kills on server then let client use those values.

I would go a bit more indepth although im on my phone currently