Hey, i decided to work on a chunk loader/unloader soo i made this script:
local Grid = 200
local RenderDistance = 16
local YPosition = 10
local spacing = 2
local Chunks = {}
local Player = workspace.Player
local Actor = game:GetService("ServerScriptService").Actor
local function Generate(GridSize: number)
for i = 0, GridSize^2 - 1 do
local x = (i % GridSize) * spacing
local y = math.floor(i / GridSize) * spacing
Chunks[i] = {["x"] = x,["y"] = y, index = i}
end
end
local function ShowParts()
for i, v in Chunks do
local Part = Instance.new("Part")
Part.Anchored = true
Part.Name = i
Part.Size = Vector3.new(spacing,1,spacing)
Part.Color = Color3.new(1,0,0)
Part.Position = Vector3.new(v.x, YPosition, v.y)
Part.Parent = workspace.Parts
if i%400 == 0 then task.wait(0) end
end
end
local VisibleChunks = {}
local function GetPartsToUpdate(): {Part} & {Part}
local PreviousVisibleChunks = {}
local Updated = false
local currentPosition = Player.Position
for i, v in Chunks do
local diff = (Vector3.new(v.x,YPosition,v.y) - currentPosition).Magnitude
if diff > RenderDistance * spacing then
if VisibleChunks[i] then VisibleChunks[i] = nil; PreviousVisibleChunks[i] = true; Updated = true else continue end
else
if VisibleChunks[i] then continue end
if not Updated then Updated = true end
VisibleChunks[i] = true
end
end
if not Updated then return {}, {} end
return PreviousVisibleChunks, VisibleChunks
end
local function UpdateParts()
while true do
task.desynchronize()
local UnloadParts, LoadParts = GetPartsToUpdate()
task.synchronize()
task.spawn(function()
for i, v in UnloadParts do
workspace.Parts[i].Color = Color3.new(1,0,0)
if i%8 == 0 then task.wait(0) end
end
end)
task.spawn(function()
for i, v in LoadParts do
workspace.Parts[i].Color = Color3.new(1,1,1)
if i%8 == 0 then task.wait(0) end
end
end)
task.wait(1/3)
end
end
Generate(Grid)
ShowParts()
UpdateParts()
I used parrarel luau to loop through arrays, also i only change colors to see if this system actually works, what it does is it spawns grid of parts, then it checks distance between chunks and player cube, if this distance is too big then it’s added to previous chunks soo it will be updated as hiden in next iteration
Problem is that i don’t know what to add to make this code more efficient, soo i can use it in actual game, the only thing i think about is making this loop very slow or adding chunk loading yield, any other ideas tho?