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

How to detect if a player is sitting on a meshpart?

I want to make a script that detects if a seat is being used and if it is it will take 99 health of the player that is using the seat here is my code:

local seat = script.Parent.Seat
local player = script.Parent.Parent.Parent.Parent.Parent.Players.LocalPlayer

seat.Touched:connect(function()
game.Players.LocalPlayer.Character.Humanoid:TakeDamage(100)
end)

2 answers

✓ Accepted answer

This answer may be a bit better than the last because it removes some of the bugs you will encounter.


  1. Check if the seat's state has changed

  2. Determine if that is because a player stuck their fat @$$es on it

  3. Murder time.


Here is how that would go.

local seat = workspace.Seat
seat.Changed:connect(function(property)
    if property ~= 'Occupant' then return end
 
    local occupant = seat.Occupant
    if occupant then
        local character = occupant.Parent
        local player = game.Players:GetPlayerFromCharacter(character)
        if player then
            print(("Player %q just sat on the seat"):format(player.Name))
	    character.Humanoid.Health = character.Humanoid.Health - 99
        end
    end
end)

Part of this modified script has been directly taken from: https://wiki.roblox.com/index.php?title=API:Class/Seat/Occupant

If this helped... Please click the accept button.

I don't know why would you want to have a MeshPart that depletes your health when seated on, but I recommend just making a Seat in Workspace. It will always be square.

If you want your player's health to be 1 when sitting you can just do this:

-- Script in the Seat
local seat = script.Parent

seat.Touched:connect(function(hit) -- Hit is the part that touched the seat
	if hit.Name ~= game.Workspace then -- Workspace keeps touching the seat so you need to put this line if you don't want errors in your output
		hit.Parent.Humanoid.Health = 1
	end
end)

However, if you want it to deplete player's health by 99 then that's more complicated because the server keeps firing the function constantly and would cause instant death.

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