How do I get the next music to play after the previous one ends?

I’m trying to get the next music to start playing after the previous one ends randomly. Can I make it easier?


local SoundBlock = script.Parent:WaitForChild("SOUND", true)
local Sound_1 = SoundBlock:WaitForChild("AB")
local Sound_2 = SoundBlock:WaitForChild("DТ")
local Sound_3 = SoundBlock:WaitForChild("Sound3")
local Sound_4 = SoundBlock:WaitForChild("Sound4")

local Sounds = {}

for _, v in pairs(script.Parent.SOUND:GetChildren()) do
	table.insert(Sounds, v)
end

local function RandomSound()
	return(math.random(1, #SoundBlock:GetChildren()))
end

Sounds[RandomSound()]:Play()


Sound_1.Ended:Connect(function()
	Sounds[RandomSound()]:Play()
end)

Sound_2.Ended:Connect(function()
	Sounds[RandomSound()]:Play()
end)

Sound_3.Ended:Connect(function()
	Sounds[RandomSound()]:Play()
end)

Sound_4.Ended:Connect(function()
	Sounds[RandomSound()]:Play()
end)

You could put those sounds in a table like:

local Sounds = {
	Sound1 = "",
	Sound2 = ""
}

And loop through this instead of making 4 different :Connects.
Looks a little cleaner.

1 Like

Ok, but I can’t understand how do I make a play-loop for this table

I’d say something like this would do:

local SoundBlock = script.Parent:WaitForChild("SOUND", true)
local Sounds = SoundBlock:GetChildren()

local function RandomSound()
	return(math.random(1, #SoundBlock:GetChildren()))
end

Sounds[RandomSound()]:Play()

for _,Sound in pairs(Sounds) do
	Sound.Ended:Connect(function()
		Sounds[RandomSound()]:Play()
	end)
end

Not tested in studio since I can’t at this moment. But it should work!

1 Like

It’s finally working, thank you

1 Like