I’m making a gun script and it works completely fine, and it is smooth with the use of :SetNetworkOwner(), but the thing is when I try testing it shooting 30 shots a second, it starts lagging quite bad. Is this normal or is this something that isn’t optimized enough?
Here is the code:
Local Script
local down = false
local mouse
local db = 0
script.Parent.Equipped:Connect(function(m)
mouse = m
m.Button1Down:Connect(function()
down = true
end)
m.Button1Up:Connect(function()
down = false
end)
end)
script.Parent.Unequipped:Connect(function()
mouse = nil
down = false
end)
game:GetService("RunService").RenderStepped:Connect(function(step)
if mouse and down then
for i = 1, 12 do -- to test shotgun, shooting 12 per bullet and 5 times a second for this test
script.Parent.Shoot:FireServer(mouse.Hit.Position) -- remote event, see server script
end
db = 1 / 5
end
db -= step
end)
Server:
local plr = script.Parent.Parent.Parent -- messy ikr
local handle = script.Parent.Handle -- obviously a part
local main = coroutine.create(function(pos) -- Look lower for coroutine explanation, this is quite simple
local function Fire() -- shooting function
local start = plr.Character.Head.Position
local cf = CFrame.lookAt(start, pos)
local beam = Instance.new("Part")
beam.Color = Color3.new(1, 0, 0)
beam.Transparency = .7
beam.Material = Enum.Material.Neon
beam.Name = "Beam"
beam.Size = Vector3.new(.1, .1, 4)
beam.Locked = true
beam.CanCollide = false
-- cframe manipulation and stuffs
beam.CFrame = cf * CFrame.new(0, 0, -beam.Size.Z / 2)
beam.Velocity = cf.LookVector.Unit * 200
-- activate bullet
local force = Instance.new("BodyForce", beam)
force.Force = Vector3.new(0, 0, 0)
beam.Parent = workspace
force.Force = Vector3.new(0, workspace.Gravity * beam:GetMass(), 0)
beam:SetNetworkOwner(plr)
-- add debris
game.Debris:AddItem(beam, 5)
end
while 1 do
-- what this does is just run Fire() and wait until this coroutine is called again, then it redefines pos which is mouse.Hit.Position
Fire()
pos = coroutine.yield()
end
end)
script.Parent.Shoot.OnServerEvent:Connect(function(player, pos)
if player == plr then -- just a check i guess
coroutine.resume(main, pos) -- run the coroutine and send mouse.Hit.Position
end
end)
Here is a video with Summary and Micro-Profiler
Edit: Added vid and corrected transparency property
tl;dr I am having performance issues with a gun shooting 30+ times a second, is this normal?
Thanks.