What is wrong with my voxelization script?

I tried to make a destruction script, but it became absurdly laggy. By that i mean freezes for no reason, even with low part count. Freezes with high (200+) and low (4) part count are almost same, i don’t know what to do.
Here’s the script. It’s only a concept right now, so it’s just a legacy script.

local function subdivideByCubes(part: BasePart, cubeSize: Vector3, resizeToPart:boolean) :(Folder)
	
	local handler = Instance.new("Part")
	handler.CFrame = part.CFrame
	handler.Size = part.Size
	handler.Parent = part.Parent
	part.Parent = nil
	local cubesize = cubeSize or Vector3.new(1, 1, 1)
	local xCount = math.round(part.Size.X / cubesize.X)
	local yCount = math.floor(part.Size.Y / cubesize.Y)
	local zCount = math.round(part.Size.Z / cubesize.Z)
	if xCount ==0 or yCount ==0 or zCount == 0 then
		warn("One of the sides is way too small for the cubes with size:", cubeSize) 
			warn("Part size:", part.Size)
	end
	
	local cube = Instance.new("Part")
	local startPosition = part.Position - ((part.CFrame.XVector * (part.Size.X / 2 - cubesize.X / 2)) + (part.CFrame.YVector * (part.Size.Y / 2 - cubesize.Y / 2)) + (part.CFrame.ZVector * (part.Size.Z / 2 - cubesize.Z / 2)))
	local folder = Instance.new("Folder")
	
	for Index = 1, (xCount * yCount * zCount) do
		cube.Size = cubesize
		cube.Anchored = true
		cube.Position = startPosition + 
			(part.CFrame.XVector * (Index % xCount) * cubesize.X) + 
			(part.CFrame.YVector * (math.floor(Index / xCount) % yCount) * cubesize.Y) + 
			(part.CFrame.ZVector *( math.floor(Index / (xCount * yCount))) * cubesize.Z)
		
		cube.Parent = folder
		cube = Instance.new("Part")
	end
	script:Destroy()
	folder.Parent = workspace
	handler:Destroy()
	part:Destroy()
	return folder
end

task.wait(5)

subdivideByCubes(script.Parent, Vector3.new(4, 4, 4), false)

I’m not sure if you’ve solved this by now, but it is because your for loop increases in complexity on the order of O(n^3) with the size of parts, if you make the part twice as long on just a single axis, that loop will take twice as long to complete. You can imagine its worse if you also scale up on the other two axis.

I have actually been developing a system to make these kinds of destructions optimized and simple, see the thread here if you are still interested:

1 Like

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