Hello! I'm just learning how to script. Someone helped me while I was making a script for a button that would change the song playing every time it was pressed, and I learned quite a lot from that!! I'm now trying to modify the script so that it randomizes what song plays when the button is pressed, and also make it so the button can only be pressed every 30 seconds.
Here is my script after i've recieved help from the accepted answer below!!
01 | local songs = { |
06 | } |
07 | local songLength = #songs |
08 | local Sound = script.Parent.Parent.Sound |
09 | local CD = script.Parent |
10 | local randomGenerator = Random.new() |
11 | local selected = 0 |
12 | Sound.Pitch = 1 |
13 | Sound.Volume = 3 |
14 | Sound.Name = "Player" |
15 | song 1 = "http://www.roblox.com/asset/?id=2538961789" --paste last song id here |
Here is the original script:
01 | local songs = { |
06 | } |
07 | local songLength = #songs |
08 | local Sound = script.Parent.Parent.Sound |
09 | local CD = script.Parent |
10 | local selected = 0 |
11 | Sound.Pitch = 1 |
12 | Sound.Volume = 3 |
13 | Sound.Name = "Player" |
14 | song 1 = "http://www.roblox.com/asset/?id=2538961789" --paste last song id here |
15 | Sound.SoundId = song 1 |
here is my modified version that doesn't work :( the output states: (Workspace.Model.Button.ClickDetector.Script:19: attempt to perform arithmetic (mod) on table and number) --I sort of understand this, but I don't know how else to make it Random
01 | local songs = { |
06 | } |
07 | local songLength = #songs |
08 | local Sound = script.Parent.Parent.Sound |
09 | local CD = script.Parent |
10 | local selected = 0 |
11 | Sound.Pitch = 1 |
12 | Sound.Volume = 3 |
13 | Sound.Name = "Player" |
14 | song 1 = "http://www.roblox.com/asset/?id=2538961789" --paste last song id here |
15 | Sound.SoundId = song 1 |
If you look at the documentation for Random, you'll see that it's used a little differently than the way you've used it.
Instead, at the top of your script, you need to create a random number generator:
local randomGenerator = Random.new()
Then, where you're setting selected
, you can use the Random:NextInteger
method:
selected = randomGenerator:NextInteger(1, #songs)
edit: Forgot about the wait part.
Your wait(30)
solution didn't work because that event is going to run asynchronously, i.e. in parallel (sorta) to the rest of your code. So if you press the button once, wait ten seconds, and click it again, the handler from the first click will be wait
ing, but the handler from the second click doesn't care and will be executed immediately anyways.
What you're looking for is called a debounce. Here's a great article on it: https://developer.roblox.com/en-us/articles/Debounce