Is there any way to optimize this script?

Hi,

I have a car spawner script, but causes extreme lag when someone spawns a car.
Also, I have tried everything to coroutines and “–!native” but nothing seems to help.

Is there any way to optimize this?

SpawnCarEvent.OnServerEvent:Connect(function(player, carName)

	local Car = ServerStorage:FindFirstChild("Cars"):FindFirstChild(carName)
	local CurCar = game.Workspace:FindFirstChild(player.Name .. 'sCar')
	if CurCar then
		removecar(CurCar)
	end
	if Car then
		local clonedCar = Car:Clone()
		coroutine.wrap(function()
		task.wait(3)
		for i, v:BasePart in ipairs(clonedCar:GetDescendants()) do
		
			if v:IsA("BasePart") and v:IsDescendantOf(workspace) then
				local c, e = v:CanSetNetworkOwnership()
				if c then
					v:SetNetworkOwner(player)
					end
				
			end
		end
end)()

You could define Cars outside of the event and in the OnServerEvent you change the Car declaration to this:

local Car = Cars:FindFirstChild(carName)

Changing your for loop to something like this would be more efficient as it removes unnecessary checks:

for _, v in ipairs(clonedCar:GetDescendants()) do
                if v:IsA("BasePart") then
                    local canSet, _ = v:CanSetNetworkOwnership()
                    if canSet then
                        v:SetNetworkOwner(player)
                    end
                end
            end
1 Like

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