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

Randomly picking sound script only plays 3 sounds then stops, Help ?

    sounds = script.Parent:GetChildren()
while true do
local rand = math.random(#sounds)-- #sounds will be the amount of sounds in the array

sounds[rand]:Play() -- This would take the random sound and play it.
sounds[rand].Ended:Wait()
end

This script is supposed to play a random sound from it's part. Thing is it plays 3 sounds then stops. Can someone help ?

2 answers

sounds = script.Parent:GetChildren()
while true do
local rand = math.random(#sounds)-- #sounds will be the amount of sounds in the array

sounds[rand]:Play() -- This would take the random sound and play it.
sounds[rand].Ended:Wait()
end

You're referring to the script's parent without taking into account that the script itself will be put into the table when you say :GetChildren().

Fixed Code (Hopefully)

local sounds = {}
for _,sound in pairs (script.Parent:GetChildren()) do
	if sound:IsA("Sound") then
		table.insert(sounds,#sounds+1,sound)
	end
end
while true do
	local randomSong = math.random(1,#sounds)
	sounds[rand]:Play()
	sounds[rand].Ended:Wait()
end

Hope this helps

1 comment

0

Doesn't work

Here's a working version:

local sounds = {}
for i, sound in pairs(script.Parent:GetChildren()) do
	if sound:IsA("Sound") then
		table.insert(sounds, sound)
	end
end

while true do
	local song = sounds[math.random(1, #sounds)]
	
	print(song)
	
	song:Play()
	song.Ended:Wait()
end

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