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

Is this an efficient way to make a random sound list?

Asked by
Mr_Unlucky 1085 Moderation Voter
6 years ago

I'm making a script in the Workspace when the several sounds in the children of script will play at random. However, it says that it's a number value and that it cannot play. Can anyone help me fix this?

local soundlist = script.Parent:GetChildren()
while true do
    local sound = math.random(#soundlist)
    sound:Play()
    wait()
end
0
Make an array of all the sounds, then use math.random to pick a random sound. ProjectJager 62 — 6y

2 answers

Log in to vote
1
Answered by
oftenz 367 Moderation Voter
6 years ago
Edited 6 years ago

Well you can use math.randomseed which helps in randomness. Roblox's integrated functions are not very amazing however. Random Numbers

math.randomseed(tick())
local soundlist = script.Parent:GetChildren()
while true do
    local sound = math.random(#soundlist)
    sound:Play()
    wait()
end

1
doesn't work. Mr_Unlucky 1085 — 6y
0
wdym? oftenz 367 — 6y
Ad
Log in to vote
0
Answered by 6 years ago

So in your code on line 4 your line is sound:Play() but the sound variable is really just a number that the random function returned. In order to get a random sound you must index it from the list of sounds in the array soundlist. Also the random function should be used as math.random(1,#soundlist).Heres the code

local soundlist = script.Parent:GetChildren()
while true do
    local soundnum = math.random(#soundlist) -- this gets a random number
    local sound = soundlist[soundnum]-- we will get the sound in the random numbers position in the list.
    if sound.ClassName == "Sound" then -- this makes sure it is a sound
        sound:Play()
    end
    wait()
end

Note: I also added an if statement which makes sure the instance held in the sound variable is a sound that can be played, so the script doesn't error.

Also, Im not sure if you wanted this but if you play the sound, it will choose another sound and play that immediately afterwards, so you will have multiple sounds playing at once. So if you don't want that to happen you have to wait until the sound is finished playing. The best way to do this is to get the sounds timelength and wait that amount. In the code it would look like this:

local soundlist = script.Parent:GetChildren()
while true do
    local soundnum = math.random(#soundlist) -- this gets a random number
    local sound = soundlist[soundnum]-- we will get the sound in the random numbers position in the list.
    if sound.ClassName == "Sound" then -- this makes sure it is a sound
        sound:Play()
    wait(sound.TimeLength) -- waits in seconds the property of the sound, which is how long the sounds audio is.
    end
    wait()
end

Answer this question