Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

1 comment

0

Make an array of all the sounds, then use math.random to pick a random sound.

2 answers

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

2 comments

1

doesn't work.

0

wdym?

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

This discussion is preserved as it was. New answers, comments, and votes are closed.