Search code examples
roblox

Damage player when touching water terrain


I'm trying to decrease a player's health when they touch some water terrain in ROBLOX. I'm not sure why this doesn't work, but it doesn't. If someone could help me out that would be neat.

while wait() do
    local player = game.Workspace.LocalPlayer
    local headLoc = game.Workspace.Terrain:WorldToCell(player.Character.Head.Position)
    local hasAnyWater = game.Workspace.Terrain:GetWaterCell(headLoc.x, headLoc.y, headLoc.z)
    if player.Character.Humanoid.Health ~= 0 then
        if hasAnyWater then
            player.Character.Humanoid:TakeDamage(0.2)
        end
    end
end

Solution

  • If you check your output window you'll see why:

    LocalPlayer is not a valid member of Workspace
    

    LocalPlayer is in "Players", so you should declare:

    local player = game.Players.LocalPlayer
    

    So if you change that, and have it in a LocalScript for example in the StarterPlayerScripts folder, everything works just like you want.