Why is this not working?

Hello!
I am trying to detect each time if a player has their humanoid health on 0 and their team is Alive. However, my code seems to not work, and has no errors.
Code:

game.Players.PlayerAdded:Connect(function(player)
	if player.Character.Humanoid.Health == 0 and player.Team == game.Teams.Alive then
		player.Team = game.Teams.Playing
	end
end)
--This is a serverscript--

Can you help me? Thanks.

You can try this

local players = game:GetService("Players")
local teams = game:GetService("Teams")

local function playerAdded(player)
	player.CharacterAdded:Wait()
	local char = player.Character
	if char:WaitForChild("Humanoid") then -- if a humanoid is found then
		local humanoid = char:FindFirstChild("Humanoid")
		player.Character:WaitForChild("Humanoid").Died:Connect(function() -- fires when the player dies
			if player.Team == teams.Alive then
				-- code here
			end	
		end)
	end
end

players.PlayerAdded:Connect(playerAdded)

More info abut teams: Player | Roblox Creator Documentation

Thanks but it only happens once, how can I make it happen more than once?

You aren’t listening for health changes at all, meaning this only runs when the player joins the game(and may fail because most of the time player.Character is nil on join). Instead run your if statement every time the humanoid gets damaged using Humanoid.HealthChanged:

--Script inside StarterCharacterScripts(runs every time a character loads, inside that character)
local Character = script.Parent 
local Player = game.Players:GetPlayerFromCharacter(Character)
local Humanoid = Character:WaitForChild("Humanoid")

Humanoid.HealthChanged:Connect(function(health)
	if health <= 0 and Player.Team == game.Teams.Alive then 
		player.Team = game.Teams.Playing
	end 
end)
3 Likes