Is this code as optimized as it can be?

I created a muffle effect for all sounds when the player’s camera is underwater using a SoundGroup.

This code is in a local script, but I’m wondering if this will cause any frame drops or lag on the client?

local sds = game:GetService("SoundService")
local cam = workspace.CurrentCamera

local underwater = false

for i, s in pairs(workspace:GetDescendants()) do -- gets all pre-existing sounds in the game
	if s:IsA("Sound") then
		s.SoundGroup = sds.Muffle
	end
end

workspace.DescendantAdded:Connect(function(s) --detects when a new sound is added while the camera is underwater
	if s:IsA("Sound") then
		s.SoundGroup = sds.Muffle
	end
end)

function Muffle()
	if underwater == true then return end
	sds.Muffle.UnderwaterMuffle.Enabled = true
end

function Unmuffle()
	if underwater == false then return end
	sds.Muffle.UnderwaterMuffle.Enabled = false
end

rs.Heartbeat:Connect(function()
	if cam.CFrame.Y < 0 then
		Muffle()
		underwater = true
	else
		Unmuffle()
		underwater = false
	end
end)

The reason why I ask is because these functions run on every frame (heartbeat), and I’ve had problems before where I ran for i, o in pairs(workspace:GetDescendants()) do on every frame, so I took a different approach to this script.

1 Like

Don’t worry, that is plenty fine! You can make far more expensive scripts than that and still not run into frame drops. Just checking the Y position of the camera and changing one value should be nothing to worry about. One suggestion I might have is to have all sounds created have the SoundGroup already set though, so the client doesn’t need to assign that.

If, for some strange reason, this DOES cause frame drops, then there may be an issue on Roblox’s end.

Could I use RenderStepped or Stepped instead of Heartbeat and still not run into any problems?

Yeah, it doesn’t really matter where you do. It’s a really inexpensive snippet of code, and should be able to be used anywhere.