Hello, i have this simple script that selects a random sound from the childrens of the script and then it plays it if soundFrame.Visible == true
What i want to do is that if the player hits the button “Join Match” then it will stop the music, pressing the button makes soundFrame.Visible = false.
The problem is that when the player hits that button the music won’t stop, it just keeps playing it, my guess it’s that it selects a new sound instead of the one that is already there and it stops it.
I have made a lot of changes to the script but it still does the same, i have also searched on the forum for any solution but i haven’t found any.
If someone can provide a solution it would be great.
Thanks!
Here is my script:
local soundFrame = script.Parent
local sounds = script:GetChildren()
local randomIndex = math.random(1,#sounds)
local randomSound = sounds[randomIndex]
if soundFrame.Visible == true then
randomSound:Play()
elseif soundFrame.Visible == false then
randomSound:Stop()
end
That’s the full script for the random sounds, there is another script that will make the Main menu invisible and the soundFrame when the players hits “Join Match”
The problem with the code you’ve provided is simple.
if soundFrame.Visible == true then
randomSound:Play()
elseif soundFrame.Visible == false then
randomSound:Stop()
end
doesn’t work because the if statement only runs once (when the script is replicated to the client), so it won’t actually check the frame’s visibility when it does change.
I recommend using something like GetPropertyChangedSignal and listening for the Visible property of the frame
Fixed code would look something like:
local soundFrame = script.Parent
local sounds = script:GetChildren()
local randomIndex = math.random(1,#sounds)
local randomSound = sounds[randomIndex]
if soundFrame.Visible == true then
randomSound:Play()
elseif soundFrame.Visible == false then
randomSound:Stop()
end -- keep this so when the client starts, the random sound is still played
-- code below will rerun the if statement whenever the "Visible" property is changed
soundFrame:GetPropertyChangedSignal("Visible"):Connect(function()
if soundFrame.Visible == true then
randomSound:Play()
elseif soundFrame.Visible == false then
randomSound:Stop()
end
end)