How could I optimize this script? Suffers FPS drops

I’ve noticed that the longer I use this script the more my fps drops and I’m hoping to find a possible solution.

function StartRenderStep()
   RenderStepped = game:GetService("RunService").RenderStepped:Connect(function()
       print("Renderstep")
       if WA.Value ~= "" then
           if CC == "Fixed" then
               CA.CFrame = CFrame.new(GetClosestPos().Position) * CFrame.Angles(CA.CFrame:ToEulerAnglesXYZ())
               CA.FieldOfView = (1000/((CalculateMagnitude(GetClosestPos(),GetRootPart(WA.Value))*0.15)+8))+10
           elseif CC == "Onboard" then
               CA.CFrame = game.Players:FindFirstChild(WA.Value).Character.Head.CFrame
           end
       end
   end)
end

Is it possible you are connecting the same event to RenderStepped over and over again?

Yes It’s a loop, I don’t think I could use the script without the loop since it’s a spectator system which is based on how Formula 1 does there camera work

You should make sure you only have one connected event. you can do that like this:

--OUTSIDE your function
local spectateEvent = nil

--Inside your function:
if spectateEvent then
    --Disconnect old event
    spectateEvent:Disconnect()
end

--Connect new event, so there will only ever be one connected.
spectateEvent= game:GetService("RunService").RenderStepped:Connect(...)
1 Like

Just disconnect the RenderStepped event in that function.

Code:

function StartRenderStep()
	if RenderStepped then
		RenderStepped:Disconnect()
		RenderStepped = nil
	end
	
	RenderStepped = game:GetService("RunService").RenderStepped:Connect(function()
		if WA.Value ~= "" then
			if CC == "Fixed" then
				CA.CFrame = CFrame.new(GetClosestPos().Position) * CFrame.Angles(CA.CFrame:ToEulerAnglesXYZ())
				CA.FieldOfView = (1000/((CalculateMagnitude(GetClosestPos(),GetRootPart(WA.Value))*0.15)+8))+10
			elseif CC == "Onboard" then
				CA.CFrame = game.Players:FindFirstChild(WA.Value).Character.Head.CFrame
			end
		end
	end)
end
1 Like

do the above and remove the print too, printing the same thing over and over again in loops screws up performance massively

3 Likes

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