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

How to make sure the same song doesn't play twice with math.random?

I have a sound in the Workspace with a script in. I have a Table / Arrary inside the script containing 3 music IDs. How do I make sure the same song doesn't play again after it playing? Here :

Music = {177226555,156637449,186747495}

while true do
script.Parent:Stop()
script.Parent.SoundId = ""
script.Parent.SoundId = "http://www.roblox.com/Asset/?id="..Music[math.random(1,#Music)]
script.Parent:Play()
wait(script.Parent.TimeLength)
end

2 answers

✓ Accepted answer

To stop that, just store the last played ID in a variable, and check if the random ID is the same as the one in the variable. This should work:

Music = {177226555,156637449,186747495}

local Last -- Declare Last

while true do
script.Parent:Stop()
script.Parent.SoundId = ""
local RandomId -- Declare RandomId
repeat RandomId = Music[math.random(1,#Music)] until Last~=RandomId
Last = RandomId
script.Parent.SoundId = "http://www.roblox.com/Asset/?id="..RandomId
script.Parent:Play()
wait(script.Parent.TimeLength)
end


Hope it helps! Comment if you don't understand.

3 comments

0

Thanks for that! I was thinking maybe something along the lines of that, but just didn't know how to piece it together.

1

That's fine. By the way, instead of "http://www.roblox.com/Asset/?id=", you can just use "rbxassetid://", if you didn't know already

0

Alright, thanks.

A good thing to do would be to store the currently playing song in a variable and remove it from the table, then put it back after choosing the next one.

local Music,song={177226555,156637449,186747495}
while true do
	local i=table.remove(Music,math.random(#Music))
	Music[#Music+1]=song
	song=i
	script.Parent:Stop()
	script.Parent.SoundId="rbxassetid://"..song
	script.Parent:Play()
	wait(script.Parent.TimeLength)
end

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