Review on my Chunk System

Hey guys I am making a chunk system

When unloading parts it has no issues, This is what is like unloading 54937 parts in 2 seconds;


Without any fps DROP.(neither micro profiler peaks)

But when loading parts it gets a little chunky

Any ways to improve it?
Here’s source code;

local Player = game:GetService('Players').LocalPlayer
local Character

local Regions = {}
local UnloadedRegions = {};


local CheckTime = 10;

local module = {}

function module.UnloadRegion(Index)
	local Table = Regions[Index]
	if (Table) then
		UnloadedRegions[Table.Tag] = true;
		print('Unloading',Table.Tag)
		for i,v in pairs(Table.Children) do
			game:GetService('RunService').RenderStepped:Wait()
			v.Parent = game.ReplicatedStorage.Chunks[Table.Tag]
		end
	end
end;

function module.LoadRegion(Index)
	local Table = Regions[Index]
	if (Table and UnloadedRegions[Table.Tag] == true) then
		UnloadedRegions[Table.Tag] = nil;

		print('Loading',Table.Tag)
		for i,v in pairs(game.ReplicatedStorage.Chunks[Table.Tag]:GetChildren()) do
			game:GetService('RunService').RenderStepped:Wait()
			v.Parent = Table.Model;
		end
	end
end;

function module.LoadAllRegions()
	Regions = {};
	for i,v in pairs(workspace.Chunks:GetChildren()) do
		local orientation, size = v:GetBoundingBox()
		table.insert(Regions,{Model = v,Position = orientation.Position,Size = size,Tag = v.Name,Children = v:GetChildren()})
		local Folder = Instance.new("Folder")
		Folder.Parent = game.ReplicatedStorage.Chunks;
		Folder.Name = v.Name;
	end
end

function module.StartChunks()
	coroutine.wrap(function()

		module.LoadAllRegions()

		Character = Player.Character or Player.CharacterAdded:Wait()
		while wait(CheckTime) do
			for i,v in pairs(Regions) do
				local Position,Size = v.Position,v.Size;
				if (Player:DistanceFromCharacter(Position) > (Size.Magnitude * 1.5)) then
					if (UnloadedRegions[v.Tag] == nil) then
						module.UnloadRegion(i)
					end
				else
					if (UnloadedRegions[v.Tag] == true) then
						module.LoadRegion(i)
					end
				end
			end
		end
	end)()
end

return module

6 Likes

Were you having performance issues without the renderstep wait?

If you want things to load in more quickly then I’d suggest changing how often you have that wait. Perhaps one wait per loadRegion call would be better?

Also a random code style suggestion - you can condense these nested if statements:


if (Player:DistanceFromCharacter(Position) > (Size.Magnitude * 1.5)) then
	if (UnloadedRegions[v.Tag] == nil) then
		module.UnloadRegion(i)
	end
else
	if (UnloadedRegions[v.Tag] == true) then
		module.LoadRegion(i)
	end
end

to this:


if (Player:DistanceFromCharacter(Position) > (Size.Magnitude * 1.5)) and (UnloadedRegions[v.Tag] == nil)  then
	module.UnloadRegion(i)
elseif  (UnloadedRegions[v.Tag] == true) then
	module.LoadRegion(i)
end