Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Detecting when the local player has died?

Asked by 6 years ago

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?

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 Gavinboy3000 98 — 6y

3 answers

Log in to vote
0
Answered by 6 years ago

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)
0
i was gonna answer before u but my internet went out Gavinboy3000 98 — 6y
0
I changed my code as shown below, any ideas why it still won't work for me? GarryGecko99 30 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

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

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? GarryGecko99 30 — 6y
Log in to vote
0
Answered by 6 years ago

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?

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. User#19524 175 — 6y
0
You should put your if statement inside a HealthChanged event like I did. User#19524 175 — 6y

Answer this question