Hello, I was wondering how I could optimize this script?
local RS = game.ReplicatedStorage
local Flashlight = RS.LocalCamFlash.Light
local RemoteEvent = RS.LocalPlayerFlashlight
local cam = workspace.CurrentCamera
local flash = Flashlight:Clone()
flash.Parent = cam
local RunService = game:GetService("RunService")
local mouse = game.Players.LocalPlayer:GetMouse()
local TS = game:GetService("TweenService")
local ti = TweenInfo.new(.1, Enum.EasingStyle.Sine)
RemoteEvent.OnClientEvent:Connect(function(char,UpperTorso,Flashlight, plr)
if plr.Name == game.Players.LocalPlayer.Name then
Flashlight.Handle.Light.Light.Enabled = false
Flashlight.Handle.Light.Shadow.Enabled = false
end
end)
RunService.RenderStepped:Connect(function()
if flash then
flash.LocalTransparencyModifier = -math.huge;
flash.Position = cam.CFrame.Position
TS:Create(flash,ti,{CFrame = CFrame.lookAt(flash.Position, mouse.Hit.Position)}):Play()
end
end)
It does the job of being a flashlight that follows the camera but it makes the player lag whenever they move their camera.
My Luau/Lua Trained AI on Python gave me this. I would try it. “uses GPT-4”
The lag issue you’re experiencing might be due to the RenderStepped event firing too frequently. To reduce the lag, you can try modifying your code as follows:
local RS = game.ReplicatedStorage
local Flashlight = RS.LocalCamFlash.Light
local RemoteEvent = RS.LocalPlayerFlashlight
local cam = workspace.CurrentCamera
local flash = Flashlight:Clone()
flash.Parent = cam
local mouse = game.Players.LocalPlayer:GetMouse()
local TS = game:GetService("TweenService")
local ti = TweenInfo.new(.1, Enum.EasingStyle.Sine)
local prevPos = cam.CFrame.Position
RemoteEvent.OnClientEvent:Connect(function(char, UpperTorso, Flashlight, plr)
if plr == game.Players.LocalPlayer then
Flashlight.Handle.Light.Light.Enabled = false
Flashlight.Handle.Light.Shadow.Enabled = false
end
end)
game:GetService("RunService").RenderStepped:Connect(function()
if flash then
flash.LocalTransparencyModifier = -math.huge
local newPos = cam.CFrame.Position
if newPos ~= prevPos then
flash.CFrame = CFrame.lookAt(newPos, newPos + cam.CFrame.LookVector)
prevPos = newPos
end
TS:Create(flash, ti, { CFrame = CFrame.lookAt(flash.Position, mouse.Hit.Position) }):Play()
end
end)
In this modified code, I’ve introduced a prevPos variable to store the previous camera position. The flashlight’s position is only updated when the camera position changes, reducing unnecessary updates and potentially improving performance.
Additionally, I’ve updated the if plr.Name == game.Players.LocalPlayer.Name condition to if plr == game.Players.LocalPlayer for better comparison.
Give this updated code a try and see if it helps alleviate the lag issue.