Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I add a sound to all my speakers?

I have three "speakers" that need a sound added to them. So I made a subroutine that adds the sound from a Table but it stopped working as soon as I added the WaitTime variable and only one "speaker" gets a sound. How can I make all my "speakers" get sounds? I'm doing it this way because I need this to work universally for different speakers. P.S I know I'm not calling the function in this code.

function AddSounds(Object, Sound)
	if Object:IsA("Part") then
		if Object.Name == "Speaker" then
			local S = Sound:Clone()
			S.Parent = Object
			WaitTime = S.TimeLength
			S:Play()
			wait(WaitTime)
			S:Destroy()
			SoundAdded = false
			print("Ready to play")
		end
	end
	for _, child in ipairs(Object:GetChildren()) do
		AddSounds(child, Sound)
	end
end

1 answer

✓ Accepted answer

The best way to fix this is by using coroutines

Coroutines create a separate thread where you can run your loops without disturbing the flow of your main script.

There are 2 key functions that you require:

coroutine.resume(c) - c being a created coroutine

coroutine.create(f) - f being a function

You must create a coroutine before using it (by calling resume()) There are a couple of ways of making a coroutine, I will show you one.

coroutine.resume(coroutine.create(function() 
 -- Your either looped script or for script
end))

So, for you it should go like this:

function AddSounds(Object, Sound)
    if Object:IsA("Part") then
        if Object.Name == "Speaker" then
	    coroutine.resume(coroutine.create(function() 
            	local S = Sound:Clone()
            	S.Parent = Object
          	WaitTime = S.TimeLength
          	S:Play()
           	wait(WaitTime)
         	S:Destroy()
          	SoundAdded = false
           	print("Ready to play")
            end))
        end
    end
    for _, child in ipairs(Object:GetChildren()) do
        AddSounds(child, Sound)
    end
end

By the way, your print("Ready to play") will print once the play has finished, which I do not believe you want. Add it before S:Play()

Hopefully that should work for you.

2 comments

0

Most well explained coroutine I've ever seen on this site. Thanks mate.

0

I'd recommend using "coroutine.wrap" instead; it's similar to "coroutine.create" & "resume," but w/o the long typing, +, imo, it's simpler to use. Even better, I highly recommend using "spawn" over using the "coroutine"s, as it is much, much simpler to use, and gets the job done.

This discussion is preserved as it was. New answers, comments, and votes are closed.