Sound playing at wrong time

I wanted a sound to play when the player enters the Vehicle, but for some reason when I enter the Vehicle, the sound plays, even when I leave. How do I only play the sound when I leave?

Code:

local Sound = script.Parent.CarStartUp
local Seat = script.Parent

Seat:GetPropertyChangedSignal("Occupant"):Connect(function()
	if Seat.Occupant ~= false then
		Sound:Play()
		Sound.Ended:Wait()
	elseif Seat.Occupant ~= true then
		Sound:Stop()
	end
end)
1 Like

Hi @Not_Jdlranger, the Occupant proprety of Seat cannot be a boolean. This mean that true and false won’t work. The Occupant proprety can contains a “path to a object”. This mean that to know if there is a object mentioned in the Occupant proprety, you need to verify if the proprety is not egual to nil (nothing)
The following script should work :

local Seat = script.Parent

Seat:GetPropertyChangedSignal("Occupant"):Connect(function()
	if Seat.Occupant ~= nil then
		print("playing")
	else
		print("stop")
	end
end)

You can learn more about Seat on the roblox documentation.

The issue with your code is that the GetPropertyChangedSignal for the “Occupant” property is triggered whenever any change happens to the property, including when the occupant enters or leaves the seat. Therefore, both conditions in your if statement will always be true at some point.

local Sound = script.Parent.CarStartUp
local Seat = script.Parent
local wasOccupied = false

Seat:GetPropertyChangedSignal("Occupant"):Connect(function()
    local isOccupied = Seat.Occupant ~= nil

    if wasOccupied and not isOccupied then
        Sound:Play()
        Sound.Ended:Wait()
    elseif not wasOccupied and isOccupied then
        Sound:Stop()
    end

    wasOccupied = isOccupied
end)

Thank you so much Med! You saved my game!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.