Math.random error for music

Hi developers:

So I’m trying to have music in my game, so I made a table in my script with all of the music IDs, but I wanted the selection of the music to be random. So I used math.random() to help me, but it causes an error when I put ti into my for loop:

local music = {"5054555073", "279206904", "639750143", "606853371", "279207008", "365815608", "162457975", "188828549", "649560917"}
local sound = script.Parent.Sound
local muted = false

while true do
	for i = math.random(#music, 1) do
		sound.SoundId = "rbxassetid://"..music[i]
		wait(2.5)
		sound:Play()
		wait(sound.TimeLength)
	end
end

The do is underlined in red, which meant there was an error. I’m new to scripting, so I’m not sure what went wrong. Could someone help me out with where I should put math.random() and why it’s not working in the for loop?

Thanks!

I’m fairly new to scripting myself, although, I think this would work:

while true do
    local option = math.random(1, #music)
    sound.SoundId = "rbxassetid://"..music[option]
    wait(2.5)
    sound:Play()
    wait(sound.TimeLength)
end

I may be wrong. Please correct me if I am.

2 Likes

Well done for putting your music into a table and attempting to make it loop. Try out the code below as it should give you the result you are looking for.

local music = {"5054555073", "279206904", "639750143", "606853371", "279207008", "365815608", "162457975", "188828549", "649560917"}
local sound = script.Parent.Sound

while wait() do -- repeats continuously 
	sound:Stop() 
	if not sound.IsPlaying() then -- checks if the sound has stopped, if so the script will move on.
		local chosenSong = music[math.random(1, #music)] -- loops through the music table and selects a random ID
		sound.SoundId = "rbxassetid://"..chosenSong
		sound:Play()
		wait(1)
		wait((sound.TimeLength)-1) -- waits the length of the song (-1)
	end
end
1 Like

I suppose this would be an alternate way - thanks for helping!

1 Like

Yes, both scripts do the exact same thing, just in a different way. :slight_smile:

I know this old thread, but you can put math.radom(#music), it still works! :smiley: