Help Improving Render Distance Script

  1. What do you want to achieve?
    Lower Script Activity.

  2. What is the issue?
    High Script % Activity

So i found this Render Script on the DevForum a while back, it has worked great. But one day im was trying to see why my game feels laggy, mainly before you die for the first time. Found out this script uses Around 70% Activity when you first join the game, and after first death drops to Around 40% Activity.

My Game has many levels (18 so far), all fairly simple, made from parts and custom meshes placed throughout. Each level has less then 60k Triangles, so technically i could remove the script and it would run better, as poly count is not an issue. The Problem is some levels don’t have walls, so i need every other level to be invisible, hence the render script.

I’m aware this script may be using high activity as there are many parts it needs to scan and update, so i tried to union as much as i can, both in roblox and some models in blender. still getting Roughly 68% when you first join and Around 38% after your first death. Not sure how this script can be improved or any workarounds.

The code:

-- local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Workspace = game:GetService("Workspace")
local RunService = game:GetService("RunService")


local LocalPlayer = Players.localPlayer

local RenderCache = ReplicatedStorage:WaitForChild("RenderCache")

local Character = script.Parent

local HumanoidRootPart = Character:WaitForChild("HumanoidRootPart")

local RenderDistance = 850




local Render = Workspace:WaitForChild("Render")

local Parts ={}


function Scan()
	for _, Object in next, Render:GetChildren() do
		table.insert(Parts, Object)
		Object.Parent = RenderCache
		
	end

	for _, Object in next, RenderCache:GetChildren() do
		table.insert(Parts, Object)
		Object.Parent = RenderCache
	end
	
end

function GetPart(Object)
	if (Object:IsA("BasePart")) then
		return Object
	else
		for _, Obj in next,Object:GetChildren() do
			return GetPart(Obj)
		end
	end
	return nil
end

function Update()
	for _, v in next, Parts do
		local Part = GetPart(v)
		if (Part) then
			local Distance = (Part.CFrame.p - HumanoidRootPart.CFrame.p).Magnitude
			
			Distance = math.floor(Distance + 0.5)
			
			if (Distance <=RenderDistance) then 
				v.Parent = Render
			else
				v.Parent = RenderCache
				
			end
		end
	end
	
end

Scan()

RunService:BindToRenderStep("RenderSys", 1, Update)

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

is this a local script or a server script?

Instead of doing this, why not just hide all of the other level once you teleport to the new level. This would be way more optimized.