Why does my script cause the game to crash?

A script I’ve made has been causing me problems. The intended purpose of this script is to play one of the 9 sounds at random, and after 2 seconds, once the sound has finished, play another sound at random. The script is to repeat this process indefinitely. This is the script:


local soundStorage = 
	{"rbxassetid://170772629", "rbxassetid://156515659", 
		"rbxassetid://156515616", "rbxassetid://170772549", 
		"rbxassetid://170772523", "rbxassetid://170772514", 
		"rbxassetid://170772514", "rbxassetid://156515689", 
		"rbxassetid://156515604"}
local speak = script.Parent.Speak
local debounce = true

function playSound()
	debounce = false
	local randomSound = soundStorage[math.random(1, #soundStorage)]
	speak.SoundId = randomSound
	speak:Play()
	speak.Ended:Connect(function()
		wait(2)
		debounce = true
		if debounce then
			playSound()
		end
	end)
end

if debounce then
	playSound()
end

The script works as it should, however, there seem to be very drastic performance issues once this script has run for a few seconds, causing tremendous lag and eventually crashing the game or studio. Can anyone help me figure out what I did wrong?

if its to run indefinitely, try keeping the function call outside in a while loop and for the crash im not sure but might be fixed

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.