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

How to check if the player is sitting?

I have a seat and i want to see if the player is sitting on it, I looked at the value in ReplicatedStorage and it doesn't change. Code in the seat:

local Sitting = game.ReplicatedStorage.Sitting
script.Parent.Touched:Connect(function(hit)
	if hit:FindFirstAncestorOfClass("Model"):FindFirstChild('Humanoid') then
	local Player = game.Players:GetPlayerFromCharacter(hit.Parent)
	Sitting.Value = true
		script.Parent.TouchEnded:Connect(function(hit)
			if hit:FindFirstAncestorOfClass("Model"):FindFirstChild('Humanoid') then
					Sitting.Value = false
				end
		end)
		end
end)

1 answer

✓ Accepted answer

If the seat is this kind of seat, then you can just listen to when the "Occupant" property is changed. It is nil if no one is sitting in the seat, and the humanoid of the player that is sitting in it if someone is sitting in it.

local seat = script.Parent
local Sitting = game.ReplicatedStorage.Sitting

seat:GetPropertyChangedSignal("Occupant"):Connect(function()
	Sitting.Value = seat.Occupant ~= nil
end)

If it is just a regular part, you need to set up a more robust system.

Looking at your code, if someone is sitting in the seat, and someone else touches the seat and stops touching it, it'll set the value of the Sitting instance to false. You should only allow one person to be sitting in the seat at once, and only allow that person to be influencing the value of the Sitting instance.

local seat = script.Parent
local sitting = game.ReplicatedStorage.Sitting

local occupant

local function stoppedSitting()
	occupant = nil
	sitting.Value = false
end

seat.Touched:Connect(function(part)
	if (not occupant) then
		local humanoid = part.Parent:FindFirstChildOfClass("Humanoid")
		if (humanoid) then
			local player = game.Players:GetPlayerFromCharacter(part.Parent)
			if (player) then
				occupant = player
				sitting.Value = true
			end
		end
	end
end)

seat.TouchEnded:Connect(function(part)
	if (occupant) then
		if (part.Parent == occupant.Character) then
			stoppedSitting()
		end
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	if (player == occupant) then
		stoppedSitting()
	end
end)

With this code, you can keep track of the player that is sitting in it, so that whenever their character physically leaves it, it will set the occupant variable to nil and the value of the Sitting instance to false. If they leave the game, the TouchEnded event wouldn't fire, so you'd just have to see that if when a player leaves the game that player is the player that is currently occupying the seat.

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