Is there any way to improve this script?

hello
i made a client script that rotates alot of pars infinitly and used CollectionService to gets a table of the parts to rotate but i used coroutines to do that i donot think that is good for performance as it will create alot of threads if the game have alot of parts i want to optimize that but donot know how

task.wait(1)
local CollectionService = game:GetService("CollectionService")
local Player = game.Players.LocalPlayer
local Character :Model = Player.Character or Player.CharacterAdded:Wait()
local PrimaryPart = Character.PrimaryPart
for _,i :Part in CollectionService:GetTagged("SpinPart") do

	local function RotateParts(part : Part)
		if (part.Position - PrimaryPart.Position).Magnitude < 50 then -- the check is for opmizations only
			part.CFrame = part.CFrame * CFrame.Angles(0,1,0)
		end
		task.wait()
		RotateParts(part)
	end
	
	coroutine.wrap(RotateParts)(i) -- what i donot like in the script
end

like if the game have 500 rotating parts it will create 500 threads and that is alot
any help is appreciated and thanks

1 Like

Put the local function outside of the for loop, because every time it loops, it makes a new function. I also would put a task.wait() inside of the for loop too

2 Likes

yeah your right thanks

local CollectionService = game:GetService("CollectionService")
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local PrimaryPart = Character:WaitForChild("HumanoidRootPart")

local function RotateParts(part)
	while true do
		if (part.Position - PrimaryPart.Position).Magnitude < 50 then
			part.CFrame = part.CFrame * CFrame.Angles(0, 1, 0)
		end
		task.wait()
	end
end

for _, part in CollectionService:GetTagged("SpinPart") do
	coroutine.wrap(RotateParts)(part)
end

1 Like

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