So i've done a script so it plays music from a table and I just don't know how to make it choose again from the table when it ends
01 | local songs = { 160442087 , 705243700 } |
02 |
03 | function playmusic() |
04 | local sound = Instance.new( "Sound" , game:GetService( "Workspace" )) |
05 | if sound then |
06 | sound.SoundId = "rbxassetid://" ..songs [ math.random( 1 ,#songs) ] |
07 | sound:Play() |
08 | end |
09 | end |
10 |
11 | playmusic() |
Firstly, let's use an infinite loop (while true do ... end
) to have the music system function indefinitely:
1 | while true do |
2 | -- ... |
3 | end |
Now, we'll pick and play a random song at the beginning of the statement body. Instead of using math.random
, we'll use the recommended Random
object; the algorithm provides more randomised numbers. According to some developers, math.random
has been updated to use this new algorithm anyway, but I cannot confirm this. We'll also refrain from using the second parent parameter of Instance.new
, as it is deprecated:
01 | local songs = { |
02 | 160442087 , |
03 | 705243700 , |
04 | } |
05 | local sound |
06 | -- Create a new Random. |
07 | local random = Random.new() |
08 |
09 | while true do |
10 | -- Pick and play a random song. |
11 | sound = Instance.new( "Sound" ) |
12 | sound.SoundId = "rbxassetid://" .. songs [ random:NextInteger( 1 , #songs) ] |
13 | sound.Parent = workspace |
14 | sound:Play() |
15 | end |
Lastly, let's use the Sound.Ended
event to wait until the song ends. Once it ends, we'll start again:
01 | local songs = { |
02 | 160442087 , |
03 | 705243700 , |
04 | } |
05 | local sound |
06 | -- Create a new Random. |
07 | local random = Random.new() |
08 |
09 | while true do |
10 | -- Pick and play a random song. |
11 | sound = Instance.new( "Sound" ) |
12 | sound.SoundId = "rbxassetid://" .. songs [ random:NextInteger( 1 , #songs) ] |
13 | sound.Parent = workspace |
14 | sound:Play() |
15 | -- Yield until the sound ends. |
16 | sound.Ended:Wait() |
17 | end |
I have a script but this changes your table. Try using this script:
01 | local songs = { 160442087 , 705243700 } |
02 |
03 |
04 | local sound = Instance.new( "Sound" , game:GetService( "Workspace" )) |
05 | while true do |
06 | if sound then |
07 | sound.SoundId = "rbxassetid://" ..songs [ math.random( 1 ,#songs) ] |
08 | sound:Play() |
09 | wait(sound.Timelength) |
10 | end |
11 | end |