How can I optimize this code?

I made a Laser eyes script awhile ago and I started noticeing that it lags my game when its active. So im pretty sure its the reason for some lag in my game. I have a server script and a client script to handle it

Client script (StarterCharacterScripts)

local LatestStartPos
local LatestEndPos
local Thickness
local Damage
local Hit
local Dir
local TI = TweenInfo.new(0.1)
local CrosshairNormalPos = UDim2.fromScale(0.5,0.25)
local DefaultImage = game.Players.LocalPlayer:GetMouse().Icon
game.ReplicatedStorage:WaitForChild("GetLaserDetails").OnClientInvoke = function()
	return LatestStartPos, LatestEndPos,Dir, Thickness,Damage,Hit
end
local char = script.Parent
	local LaserFolder = game.ReplicatedStorage.LaserBeam:Clone()
	local HRP:Part = char:WaitForChild("Head")
	LaserFolder.Name = "CleintLaser"
	LaserFolder.Parent = char:WaitForChild("HumanoidRootPart")
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = {char:GetDescendants()}
	params.FilterType = Enum.RaycastFilterType.Exclude
	params.RespectCanCollide = true
	local function ResetRay()
		local ServerLaser = char:FindFirstChild("ServerLaser")
		if ServerLaser then
			ServerLaser:Destroy()
		end
		if HRP then
			local MousePos = game.Players.LocalPlayer:GetMouse().Hit.Position
			local ray = Ray.new(HRP.Position,(MousePos-HRP.Position))
			if not game:GetService("UserInputService").MouseEnabled then
			--wportPoint.X, viewportPoint.Y/2, 0)
				game.Players.LocalPlayer.PlayerGui.CrossHair.Frame.Position = CrosshairNormalPos
			local camera = workspace.CurrentCamera
			local viewportPoint = camera.ViewportSize / 2
			local unitRay = camera:ViewportPointToRay(viewportPoint.X, viewportPoint.Y/2, 0)
			ray = Ray.new(unitRay.Origin, unitRay.Direction * 500)
			end
			Damage =LaserFolder.Damage.Value
			Thickness = LaserFolder.Thickness.Value
			local rayresult = workspace:Raycast(ray.Origin,ray.Direction,params)
			LaserFolder.Start.Position = HRP.FaceFrontAttachment.WorldPosition
			LatestStartPos = LaserFolder.Start.Position
			if rayresult and rayresult.Position then
				LaserFolder.End.CFrame = CFrame.lookAt(rayresult.Position,LaserFolder.Start.Position)
				Dir = rayresult.Position-MousePos
			end
			if rayresult and rayresult.Instance then
				Hit = rayresult.Instance
			end
			if LaserFolder.Thickness.Value >= 0.01 then
				if not game:GetService("UserInputService").MouseEnabled then
				game.Players.LocalPlayer.PlayerGui.CrossHair.Enabled = true
				end
			else
			game.Players.LocalPlayer.PlayerGui.CrossHair.Enabled = false
			end
		end
	end
	game:GetService("RunService").RenderStepped:Connect(function()
		ResetRay()
		if HRP then
		LatestEndPos = LaserFolder.End.Position	
		end
	end)

Server script (ServerScriptService)

local RefreshTime = 0.01
-- lvl system
local BannedUsers = {}
game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local LocalLaser = game.ReplicatedStorage.LaserBeam:Clone()
		LocalLaser.Parent = char
		LocalLaser.Name = "ServerLaser"
		task.spawn(function()
			while wait(0.1) do
				local Start,End,Dir,Thickness,Damage,Hit:Part = game.ReplicatedStorage.GetLaserDetails:InvokeClient(plr)
				if Thickness and Thickness > 0 then
					pcall(function()
						local hum = Hit.Parent:FindFirstChildWhichIsA("Humanoid")
						if hum then
							hum:TakeDamage(Damage)
							local Isplr = game.Players:GetPlayerFromCharacter(hum.Parent)
							if not Isplr and hum.Health <= 0 then
								-- level system 
								local LVL = hum:GetAttribute("HL")
								if not LVL then
									LVL = -1
								end
								local Hbanned = plr:GetAttribute("HLV")
								if not Hbanned then
									Hbanned = 0
								end
								if not table.find(BannedUsers,hum) and LVL >= Hbanned then
									plr:SetAttribute("HLV",Hbanned+1)
									table.insert(BannedUsers,hum)
								end
							end
						end
					end)
				end
			end
		end)
		while wait(RefreshTime) do
			local Start,End,Dir,Thickness = game.ReplicatedStorage.GetLaserDetails:InvokeClient(plr)
			if Start then
				LocalLaser.Start.Position = Start
			end
			if End then
				LocalLaser.End.CFrame = CFrame.lookAt(End,LocalLaser.Start.Position)
			end
			if Thickness then
				LocalLaser.Beam.Width0 = Thickness
				LocalLaser.Beam.Width1 = Thickness
				
			end
		
		end
	end)
	
end)

I dont really understand optimization so I will be glad if you can help me understand it

1 Like

The main problem Iā€™m noticing is that you create a while loop every time a players character is added. (lots of loops = lots of lag) Alternatively you can use a master script that loops through each players character and running all the code.

while task.wait(0.1) do 
     for i, plr in pairs(game.Players:GetChildren()) do 
        if plr.Character then 
           --the rest of your code (you may need to change it to work with this)
        end 
    end 
end

Another problem is that if you put the RenderStepped function inside of another function it can create lots of lag.

2 Likes

Even after doing that its still laggy and the fps is still going down. Now im starting to think its the terrible pathfinding I put into the npcs.

You did put that inside of a different script right? Not inside of any functions?

I replaced the function with the while task.wait(0.1) do for i, plr in pairs(game.Players:GetChildren()) do if plr.Character then --the rest of your code (you may need to change it to work with this) end end end in the server script and removed the function and replaced it with game:GetService("RunService").RenderStepped:Connect(ResetRay)