How to make a custom health script kill the player

As the title says, I want the player to die when the custom health value reaches 0, but I don’t really know how to go about doing this. My current idea is to make the while loop that controls the custom health display kill the player when it reads the health value as 0 but I don’t know how to access the player in the workspace from the local script in the player gui, how would I do so?

You can kill the player by settings the Humanoid’s .Health property to 0. I haven’t tested it but I’m pretty sure you could also change their HumanoidStateType to Enum.HumanoidStateType.Dead

I wouldn’t use a while loop to check the custom health tho… if it’s a physical object (like a NumberValue) I would use GetPropertyChangedSignal. If it’s a variable somewhere in a script, you should have a universal damage function that damages the player, and only check if they’re dead when they take damage.

For example:

local myHealth = 100 -- An example of their health stored as a variable

local function Damage(player, amount) -- A function that damages based on player or something
    myHealth -= 100
end

Damage(player, 100) -- Can call it anywhere (I'd put it in a module script)

-- From a local script:
local player = game.Players.LocalPlayer

event:Connect(function()
	if not player.Character then
		repeat task.wait() until player.Character
	end

	local Char = player.Character
	local Humanoid = Char:WaitForChild("Humanoid")
	Humanoid.Health = 0
end)

This is obviously not code you could use, and is only provided to help you understand!

This isn’t a good idea!

You should only connect an event like this after you’re certain the character and humanoid exist! And definitely not control it on the client (in a local script)

Why is that? It’s just saying if there’s not a character, wait until there is one

It depends on when it’s ran. You shouldn’t even connect the function until after the character has loaded in another script. Maybe by nesting it like:

local function onCharacterAdded(character)
     -- Then connect it
end

Thanks, I just completely forgot you could get the character from the player in a local script.

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