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 :

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

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:

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.

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.

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

Answer this question