Viewmodel script has high activity, and sometimes frops frames

You can write your topic however you want, but you need to answer these questions:

I’ve got a working viewmodel, animations and all but there’s one problem,

https://gyazo.com/a0c2ed5342292b42f7c0deeb04b71f04
The localscript that does this has a high activity rate, and sometimes it makes the game lag, (FPS wise)
I have a reason to believe it’s something to do with this line.

run.RenderStepped:Connect(function()


local function cframeToCamera()
	run.RenderStepped:Connect(function()
		gunmodelclone:SetPrimaryPartCFrame(camera.CFrame * cframeOffsetFromCamera) -- Basically, sets the position every time the player moves the camera(?) I have reason to believe this line is the culprit.
	end)
end

char.ChildAdded:Connect(function(child)
	if child:IsA("Tool") then
		gunTool = child
		gunModel = game.ReplicatedStorage[child.Name]
		gunmodelclone = gunModel:Clone()
		gunmodelclone.Parent = camera
		if script.Parent:FindFirstChild("Shirt") then
			gunmodelclone.Shirt.ShirtTemplate = script.Parent.Shirt.ShirtTemplate
			end
		gunmodelclone["Body Colors"]:Destroy()
		local bc = script.Parent["Body Colors"]:Clone()
		bc.Parent = gunmodelclone
		cframeToCamera()
		gunmodelclone.HumanoidRootPart.Anchored = false
		armhumanoid = gunmodelclone:FindFirstChild("Humanoid")
		equip = gunmodelclone:WaitForChild("Equip")
		idle = gunmodelclone:WaitForChild("Idle")
		eanim = armhumanoid.Animator:LoadAnimation(equip)
		ianim = armhumanoid.Animator:LoadAnimation(idle)
		ianim:Play()
		eanim:Play()
	end -- Basically if it detects a tool, it will get it's respective viewmodel and put it on the players camera, and fabricate it with the player's shirt and body colors.
end)

If there is an alternate solution to how I’m doing my viewmodel, I would very much appreciate it if I could be told about it. (Otherwise if there’s a fix for the lag please tell me so)

That’s to be expected since you never clean up your connections. Every time ChildAdded fires it’s creating a new connection to RenderStepped that never gets disconnected when the tool is unequipped so the connection remains alive. It’s worse that you aren’t managing RenderStepped connections well because that fires before a frame renders so if RenderStepped code is taking too long to run then it’s going to present some noticeable delays in frames.

Consider using BindToRenderStep instead, it should make your life a whole lot easier and you can avoid writing tons of boilerplate or using a connection management abstraction like Janitor. When the tool is equipped bind a function to RenderStep that updates the CFrame of the gun model (I recommend using PivotTo instead of SetPrimaryPartCFrame, the latter is intended to be deprecated and it suffers from floating point imprecisions that tear your models apart with extremely frequent calls) and then unbind it when the tool is unequipped.

1 Like

Sorry for the late response, I’ll definitely look into this!