Fix to my sit sound player?

So i have this script that should play a sound when you sit, and stop when you leave, any help?

seat = script.Parent
local event = game:GetService("ReplicatedStorage").BackpackEvent

function added(child)
	if (child.className=="Weld") then
				local human = child.part1.Parent:FindFirstChild("Humanoid")
		if human ~= nil then
			script.Parent.Sound:Play()
			event:FireClient()
		end
	 end

function removed(child2)
		script.Parent.Sound:Stop()
		end
	end

seat.ChildAdded:connect(added)
seat.ChildRemoved:connect(removed)

Instead of relying on a weld to be added and removed, you can check when the occupant of the seat changes. GetPropertyChangedSignal lets you connect an event to a specific property change, so you can just use it instead of the two other events.

local function occupantChange()
	local occupant = seat.Occupant

	if occupant then
		-- someone just got in the seat
	else
		-- someone just left the seat
	end
end

seat:GetPropertyChangedSignal("Occupant"):Connect(occupantChange)

Also, when using FireClient, you have to specify which client. You can get the player sitting in the seat by getting the character (seat.Occupant) and using GetPlayerFromCharacter on it. This could look like this: event:FireClient(game:GetService("Players"):GetPlayerFromCharacter(seat.Occupant)). Alternatively, you could use event:FireAllClients() to send the event to every player.

Edit: You also misplaced one of your ends. Instead of having two below the removed function, have one above it. Right now you’re re-defining the removed function every time that a child gets added to the seat, which means it won’t connect correctly to ChildRemoved (it won’t exist yet!). If you indented your code (which you might’ve, the forum sometimes messes formatting up) then it would have been easier to tell.

2 Likes