Search code examples
luarobloxluau

Change Player's Health


I don't know how to change the Player's Health in Roblox.

I tried this:

local Object = game.Workspace.Baseplate
Object.Touched:Connect(function()
     game.StarterPlayer.HealthDisplayDistance = 50
end)
local Killbrick = game.Workspace.Part

I thought the 3rd Line changed the health of the Player but it didn't do anything.


Solution

  • Your issue is that the Health property isn't on a Player, but rather their Character model's Humanoid.

    -- set health to 50 when touching the baseplate
    local bp = game.Workspace.Baseplate
    bp.Touched:Connect(function(otherPart)
        -- double check that the other part is a character model
        local player = game.Players:GetPlayerFromCharacter(otherPart.Parent) 
        if player then
            -- set the player's health
            player.Character.Humanoid.Health = 50
        end
    end)
    
    -- make a kill brick
    local Killbrick = game.Workspace.Part
    Killbrick.Touched:Connect(function(otherPart.Parent)
        -- double check that the other part is a character model
        local player = game.Players:GetPlayerFromCharacter(otherPart) 
        if player then
            -- kill the player
            player.Character.Humanoid.Health = 0
        end
    end)