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

Script causing unplayable lag, any help?

Im working on my game, and it has music regions. However, I got immense lag suddenly. I deleted this script and found out it was lagging me. I dont know why, or how it is causing unplayable lag, but music regions is a big part of a game. Does anyone know why or how this is happening? If so, thanks.

This is the code.

local plr = game.Players.LocalPlayer


local soundRegions = workspace:WaitForChild("SoundRegions")
soundRegions = soundRegions:GetChildren()

local soundManagement = {}

for _,region in pairs(soundRegions) do

	local info = {}

	local region3 = Region3.new(region.Position-(region.Size/2),region.Position+(region.Size/2))
	region.Transparency = 1

	info.Region = region3
	info.Sound = script.SoundRegions:FindFirstChild(region.name).Sound

	table.insert(soundManagement,info)

end

game:GetService("RunService").RenderStepped:Connect(function()

	for _,soundInfo in pairs(soundManagement) do

		local region = soundInfo.Region
		local sound = soundInfo.Sound
		local parts = workspace:FindPartsInRegion3WithWhiteList(region,plr.Character:GetDescendants())

		if #parts > 0 then

			if not sound.IsPlaying then

				sound:Play()
			end

		else

			sound:Stop()
		end
	end
end)

2 answers

✓ Accepted answer

You forgot to put a wait in the RenderStepped event, and remember RenderStepped fires every frame so of course that would be a bit laggy, but all you have to do is put a wait() in it. here's the code

local plr = game.Players.LocalPlayer


local soundRegions = workspace:WaitForChild("SoundRegions")
soundRegions = soundRegions:GetChildren()

local soundManagement = {}

for _,region in pairs(soundRegions) do

    local info = {}

    local region3 = Region3.new(region.Position-(region.Size/2),region.Position+(region.Size/2))
    region.Transparency = 1

    info.Region = region3
    info.Sound = script.SoundRegions:FindFirstChild(region.name).Sound

    table.insert(soundManagement,info)

end

game:GetService("RunService").RenderStepped:Connect(function()
	wait() -- Put The Wait Here So It Doesn't Lag Out
    for _,soundInfo in pairs(soundManagement) do

        local region = soundInfo.Region
        local sound = soundInfo.Sound
        local parts = workspace:FindPartsInRegion3WithWhiteList(region,plr.Character:GetDescendants())

        if #parts > 0 then

            if not sound.IsPlaying then

                sound:Play()
            end

        else

            sound:Stop()
        end
    end
end)

2 comments

0

Thank you! This helps alot.

0

You're welcome, i'm happy to help

I don't know much about Region3 but the best you can do is make parts around the map and with sounds that play when you touch those parts.

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