Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
Nidoxs 190
9 years ago

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 :

1Music = {177226555,156637449,186747495}
2 
3while true do
4script.Parent:Stop()
5script.Parent.SoundId = ""
6script.Parent.SoundId = "http://www.roblox.com/Asset/?id="..Music[math.random(1,#Music)]
7script.Parent:Play()
8wait(script.Parent.TimeLength)
9end

2 answers

Log in to vote
1
Answered by
RafDev 109
9 years ago

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:

01Music = {177226555,156637449,186747495}
02 
03local Last -- Declare Last
04 
05while true do
06script.Parent:Stop()
07script.Parent.SoundId = ""
08local RandomId -- Declare RandomId
09repeat RandomId = Music[math.random(1,#Music)] until Last~=RandomId
10Last = RandomId
11script.Parent.SoundId = "http://www.roblox.com/Asset/?id="..RandomId
12script.Parent:Play()
13wait(script.Parent.TimeLength)
14end

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

0
Thanks for that! I was thinking maybe something along the lines of that, but just didn't know how to piece it together. Nidoxs 190 — 9y
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 RafDev 109 — 9y
0
Alright, thanks. Nidoxs 190 — 9y
Ad
Log in to vote
0
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
9 years ago

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.

01local Music,song={177226555,156637449,186747495}
02while true do
03    local i=table.remove(Music,math.random(#Music))
04    Music[#Music+1]=song
05    song=i
06    script.Parent:Stop()
07    script.Parent.SoundId="rbxassetid://"..song
08    script.Parent:Play()
09    wait(script.Parent.TimeLength)
10end

Answer this question