I was working on a project about a year ago and I was running into an issue where my game kept crashing after a while of playing. I eventually linked it down to a sound module that was calling itself. Here is the function itself.
function SoundModule.PlayMusic(musicType)
-- code to play a sound
-- for the crashing issue to occur, I would detect when the sound finished playing and call
-- SoundModule:PlayMusic(); so new music would play
end
I’m working on a new project, but I plan on keeping a similar design for playing music. I can’t think of why a function calling itself would have issues, my guess would be it’s never GC because it’s still holding a reference to it somehow? Can somebody clarify why a module calling a function of itself would slowly crash clients and what’s going on internally?
Could you show us the code that plays the sound? Recursion doesn’t inherently crash nor hang, it usually happens when there is no base case or if the function doesn’t yield.
Hah, I actually edited the original post to remove it trying to make it look cleaner. Here it is:
function SoundModule.PlayMusic(musicType)
if (musicType == nil) then
musicType = cachedMusicType;
else
cachedMusicType = musicType;
end
local soundsRoot = localPlayer:WaitForChild("Sounds");
local musicRoot = soundsRoot.Music;
-- Lower Volume
for volume = 5, 0, -1 do
musicRoot.Volume = volume/25;
RunService.RenderStepped:Wait();
end
musicRoot:Stop();
local soundId = nil;
if (musicType == "Lobby") then
soundId = lobbyMusicCollection[math.random(#lobbyMusicCollection)];
elseif (musicType == "Match") then
soundId = matchMusicCollection[math.random(#matchMusicCollection)];
elseif(musicType == "Shop") then
soundId = shopMusicCollection[math.random(#shopMusicCollection)];
end
musicRoot.SoundId = "rbxassetid://" .. tostring(soundId);
musicRoot:Play();
-- Raise Volume
for volume = 0, 5, 1 do
musicRoot.Volume = volume/25;
wait();
end
-- detect when sound ends and call SoundModule.PlayMusic()
end
I wonder if I was never :disconnect() ing the event that detected if the music ended? I do not have the code that checked if the music ended(because it crashed the game) anymore.
Now that I’m thinking about it, I bet that was the issue.