So, i’ve been trying to make a button which pauses the current randomized music playing in my game. But, the problem is that it doesn’t pause after I click a button. The output window doesn’t say anything. There is an issue with me defining a variable for the current sound though. Please help!!
local button = script.Parent
wait(0.8)
while true do
local Sounds = workspace.MusicFolder:GetChildren()
local RandomIndex = math.random(1,#Sounds)
local RandomSound = Sounds[RandomIndex]
RandomSound:Play()
local currentsound = wait(RandomSound.TimeLength)
end
script.Parent.MouseButton1Click:Connect(function()
if play then
currentsound.Volume = 1
play = false
script.Parent.Text = "Music: ON" else
currentsound.Volume = 0
play = true
script.Parent.Text = "Music: OFF"
end
end)
The while loop is yielding the current thread, so the entire button MouseClick portion isn’t even being executed.
I also don’t see you declare a play boolean.
Try this.
local button = script.Parent
local music = workspace:WaitForChild("MusicFolder"):GetChildren()
local paused = false
local currentSong = nil
local function musicLoop()
while true do
local randomSong = music[math.random(1, #music)]
currentSong = randomSong
randomSong:Play()
randomSong.Ended:Wait()
end
end
task.defer(musicLoop) -- Wraps the musicLoop function in a coroutine, which stops it from yielding the thread
local function buttonActivated()
if paused then
currentSong:Play()
button.Text = "Music: ON"
else
currentSong:Pause()
button.Text = "Music: OFF"
end
paused = not paused
end
button.Activated:Connect(buttonActivated)
The button text doesn’t change, also do I have to call the “MouseButton1Click” function for it to work? Because the player needs to click the button to pause the current music