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

Seat (function() event help? First time scripting.

This is my first time scripting from scratch, and I need help figuring out how to make it so when I sit down, it starts a stopwatch counting up from 0. And if possible, I want it to reset when I get up.

Any help appreciated. Thank you in advance.

local seconds = script.Parent.Parent.Parent.Time

script.Parent.Text = seconds.Value

workspace.Seat.ChildAdded:Connect(function()
for i = 1,seconds.Value do
 wait(1)
 seconds.Value = seconds.Value + 1
 script.Parent.Text = seconds.Value
end)

1 answer

Using ChildAdded on an object will only execute its connected function when a child is added to its hierarchy. That's not the way Seat objects work. When a player sits or exits out of a Seat, its Occupant property is updated with the Humanoid object of the player's character sitting in the seat if the player is sitting in the seat, or nil otherwise.

Knowing this, we can look for a signal that lets us know when the Seat's Occupant property has been updated. To do so, we can use the GetPropertyChangedSignal function of all Instance objects (which includes Seats). It would end up looking something like this:

local seconds = script.Parent.Parent.Parent.Time
script.Parent.Text = seconds.Value

workspace.Seat:GetPropertyChangedSignal("Occupant"):Connect(function()
	local i = 0
	-- while there is someone sitting in the seat
	-- and while the counter hasn't maxed out yet
	while workspace.Seat.Occupant and i < seconds.Value do
		script.Parent.Text = i 
		i = i + 1 -- increment the counter
		wait(1)
	end
end)

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