Imporving a auto regenerate model script

Hey!
I have this small script I made that is simply regenerating missing parts from a model 30 seconds after they are being destroyed.

local childs = game.Workspace.City:GetDescendants()

local function Regen(Part, ModelName, Color)
	if Part.Name == "GoldenPart" then
		Part.Name = "Part"
		Part.Material = Enum.Material.Plastic
		Part.BrickColor = Color	
	end
	wait(30)
	Part.Parent = game.Workspace.City:FindFirstChild(ModelName)
end


game.Workspace.City.DescendantRemoving:Connect(function(new)
	local loc = new.Parent
	if loc then
		if new:IsA("Weld") and loc.Parent.Parent.Name == "City" then
			local PartClone = loc:Clone()
			local ModelName = loc.Parent.Name
			local Color = loc.BrickColor
			
			loc.Name = "FallenPart"
			wait(math.random(2,4))
			loc:Destroy()
			Regen(PartClone, ModelName, Color)
		end
	end
end)

Now for some reason, this script causes massive lag in the whole game, especially when the function stacks and too many parts are cloning.
Now, is there a way I can make this script cause less lag?

1 Like

As the script itself doesn’t seem to have any signs of causing lag, the issue might be apparent because of:

  • High part count inside the City model.
  • High usage of the script (a lot of models get regenerated).
  • Overall bad computer performance.

I was unable to replicate any signs of lag myself, thus i believe it might be because of the above listed reasons. Good luck with your game!

1 Like