Why doesn't my sound effects play when a button is pressed?

Hello everyone!

So I made a toggle button that would provide a light, I have 2 sounds that wanted to play when the light was on but it doesn’t.

I have two scripts and a photo of the explorer

https://gyazo.com/639c136e9bcbea6fbb8093a93e3ef734 - photo

First Script (lamp script)

state = false

function onClicked()
	wait(0.1)
	script.Parent.Sound:Play()
	if state == true then
		script.Parent.Parent.Light.PointLight.Brightness = 0
		state = false
	script.Parent.Sound:Stop()
	else if state == false then
		script.Parent.Parent.Light.PointLight.Brightness = 2
		state = true
	end
	end
end

script.Parent.ClickDetector.MouseClick:connect( onClicked )


---Second Script (Script)

script.Parent.BrickColor = BrickColor.new(2)

function onClick()
	if script.Parent.BrickColor == BrickColor.new(2) then
		script.Parent.BrickColor = BrickColor.new(1)
		script.Parent.Parent.Hid.Transparency = 1
		script.Parent.Sound:Play()
		script.Parent.Parent.Hid.SurfaceGui.TextLabel.BackgroundTransparency = 1
		script.Parent.Parent.Name = "Click to Close"
		elseif script.Parent.BrickColor  == BrickColor.new(1) then
		script.Parent.BrickColor = BrickColor.new(2)
		script.Parent.Parent.Hid.SurfaceGui.TextLabel.BackgroundTransparency = 0
		script.Parent.Sound:Play()
		script.Parent.Parent.Hid.CanCollide = false
		script.Parent.Parent.Name = "Click to Open"
	end
end

script.Parent.ClickDetector.MouseClick:connect(onClick)

I suggest you use a LocalScript instead, as it should/could play the sounds faster (in my experience) ,and put the sounds in SoundService.

1 Like

Which part doesn’t work? Just the sound or does the color changing not work either?

EDIT: I found your problem. You do :Play() and :Stop() immediately. Try to replace Stop() with script.Parent.Sound.Stopped:Wait()

not the only reason, local scripts should always generally be used for handling local input and displaying UI.

@Nacidi your code won’t run because initially the state variable is false, so this comparison:

always returns false and the code below never runs.

change the comparison to this:

      if not state then  
             state = true
             --// adjust brightness, do the rest of your stuff
             wait(1) -- cooldown between clicks
             state = false

my bad, didn’t see the other statement

1 Like

The state variable is changed below. It is like a switch. That is not the issue.

Also since LocalScripts were brought up. Yes they are better but then the sound and the light will only appear to the local player not to all of them. So depends on what the OP wants to achieve here.

(post withdrawn by author, will be automatically deleted in 1 hour unless flagged)

Here, the formating of the post is bad but I assume this is part of the if above.