In my game I have a concert stage that plays a random song from a table of different sound IDs. I also have a bell that, when clicked, should cancel/start the music.
playingMusic = false
playingMusic = true
local value = math.random(1,#music_list)
local pickedSong = music_list[value]
local waitTime = time_list[value]
music_file.SoundId = pickedSong
if playingMusic == true then
When a player clicks the bell, the music correctly stops and starts - but the functions continue to run because they were called previously and the songs start and stop abruptly. I need to find a way to cancel out playMusic() and stopMusic() entirely, if that’s even possible. I saw information regarding the Disconnect() function and task.spawn/task.cancel but wasn’t sure how to implement them into my code…
Let me know if I need to provide more info, thanks for any help!
Instead of actually cancelling it, maybe you could for example make a variable:
local stopped = false
And in the code, where there’s stopMusic(), before stopping that, do:
if stopped == true then
Like this, the music won’t stop automatically. I’m not sure if this is the best solution, but if you don’t find any better one, this might be helpful.
Yes, if you were to use threads such as task.spawn and then cancel it would stop the entire function from yielding, however here I think you don’t need to handle all that work and can just use the sound’s respected methods.
example of threads
local thread = task.spawn(function()
for i=1,10 do
What you should be doing however
local sound = script.Parent
local function play()
repeat id = music_list[math.random(1,#music_list)] until id ~= chosen
chosen = id
sound.SoundId = chosen
local function pause() -- this is the function you're probably looking for
local function resume() -- this is the function you're probably looking for
local function stop()
play() -- will play a sound
pause() -- will pause the sound
resume() -- will resume the sound
stop() -- will stop the sound
I’m really late to answering this, but thank you so much!! This simplifies my code so well, I really appreciate the feedback.