Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Detecting when the local player has died?

I'm attempting to make a GUI that displays the amount of lives the player has. Each time they die they are supposed to lose a life. I placed into the Workspace a local script with the following code.

local player = game.Players.LocalPlayer
G_lives = 3;

if (player.health == 0) then 
	G_lives = G_lives - 1
	print(G_lives)
end

I'm getting no output from this though, and I'm not exactly sure why. Could anyone explain the flaw in my code?

1 comment

0

The health isnt in the player, its in the Character or the Character's humanoid. This means you have to go player.Character.Humanoid.Health or player.Character.Health

3 answers

✓ Accepted answer

###You can’t get the health from the Player object. You get it from the Humanoid.

local plr = game:GetService("Players").LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()

char.Humanoid.HealthChanged:Connect(function(newHealth)
    print("The new health of the humanoid is:", newHealth)
end)

2 comments

0

i was gonna answer before u but my internet went out

0

I changed my code as shown below, any ideas why it still won't work for me?

The health isnt in the player, its in the Character or the Character's humanoid. This means you have to go player.Character.Humanoid.Health or player.Character.Health

1 comment

0

So I changed it so it's using the Humanoid to detect if the health is 0, but it's still not working. I have the code in a local script under Workspace. Any ideas why it's still not picking anything up?

I changed my code to this:

local player = game:GetService("Players").LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()

	if (char.Humanoid.Health == 0) then 
		G_lives = G_lives - 1
		print(G_lives)
end

I'm still not getting any output though. Did I misuse the information you guys gave me, or is it possibly because I have the localscript under workspace and it should be somewhere else?

2 comments

0

You shouldn’t wrap your if statement in brackets like you did on line 4. Remove them. Your LocalScript should be under StarterGui, StarterPack, or StarterPlayerScripts.

0

You should put your if statement inside a HealthChanged event like I did.

This discussion is preserved as it was. New answers, comments, and votes are closed.