Cloning function i made to solve script timeout exhaustion error... peak!

return function(Object: Instance, Parent: string, ChunkSize: number?): Instance
	local Tracker = 0
	local Size = #Object:GetDescendants()

	local UnAnchoredParts = {}::{BasePart}
	local ReRunScript = {}::{Script}

	local JointInstances = {}::{[JointInstance]: {Part0:string, Part1:string}}
	local Constraints = {}::{[Trail|Beam|Constraint]: {Attachment0:string, Attachment1:string}}

	local RootInstanceLookup = {}::{[Instance]:number}
	local UniqueIdLookup = {}::{[number]:Instance}

	local Track = 0
	for i,v in Object:GetDescendants() do
		while not game:GetService("RunService"):IsStudio() and game:GetService("Stats"):GetTotalMemoryUsageMb() >= 6000 do task.wait() end

		Track+=1
		Tracker+=1
		RootInstanceLookup[v] = i

		if Track >= ChunkSize then
			task.wait()
			Track = 0
		end
	end

	Tracker = 0

	local function IterateDown(Object:Instance, Track:number)
		for i,v in Object:GetChildren() do
			while not game:GetService("RunService"):IsStudio() and game:GetService("Stats"):GetTotalMemoryUsageMb() >= 6000 do task.wait() end

			Track+=1
			Tracker+=1
			local Clone = Instance.fromExisting(v)
			UniqueIdLookup[RootInstanceLookup[v]] = Clone

			if not RootInstanceLookup[v.Parent] then
				Clone.Parent = workspace
			else
				Clone.Parent = UniqueIdLookup[RootInstanceLookup[v.Parent]]
			end

			if Clone:IsA("BasePart") and not Clone.Anchored then
				Clone.Anchored = true
				table.insert(UnAnchoredParts, Clone)
			elseif Clone:IsA("Script") and Clone.Enabled then
				Clone.Enabled = false
				table.insert(ReRunScript, Clone)

			elseif Clone:IsA("JointInstance") then
				local Part0:string = RootInstanceLookup[Clone.Part0]
				local Part1:string = RootInstanceLookup[Clone.Part1]

				JointInstances[Clone] = {Part0 = Part0, Part1 = Part1}

			elseif Clone:IsA("Beam") or Clone:IsA("Trail") or Clone:IsA("Constraint") then
				local Attachment0:string = RootInstanceLookup[v.Attachment0]
				local Attachment1:string = RootInstanceLookup[v.Attachment1]

				Constraints[Clone] = {Attachment0 = Attachment0, Attachment1 = Attachment1}
			end

			if Track >= ChunkSize then
				task.wait()
				Track = 0
			end

			IterateDown(v, Track)

			v:Destroy()
		end
	end

	IterateDown(Object, 0)
	Object:Destroy()

	for i,v in JointInstances do
		i.Part0 = UniqueIdLookup[v.Part0]
		i.Part1 = UniqueIdLookup[v.Part1]
	end

	for i,v in Constraints do
		i.Attachment0 = UniqueIdLookup[v.Attachment0]
		i.Attachment1 = UniqueIdLookup[v.Attachment1]
	end

	for i,v in UnAnchoredParts do
		v.Anchored = false
	end

	for i,v in ReRunScript do
		v.Enabled = true
	end

	table.clear(UniqueIdLookup)
	table.clear(RootInstanceLookup)

	table.clear(JointInstances)
	table.clear(Constraints)
	table.clear(UnAnchoredParts)
	table.clear(ReRunScript)
end
3 Likes