Performances issues when breaking windows

I have a window that can be broken if a sword hits it. The issue is, after a few window breaks, the game starts to lag everytime someone breaks the window. I have no idea of the cause, so please help!

Code:

Module Script:

local plrenter = script.Parent.PlayerEnter

local door = {}

function door.open(doorModel, number, plr, tool)
	if doorModel:GetAttribute('Locked') == false then
		doorModel:SetAttribute("Open", true)
		local amountofshards = math.random(4,10)

		doorModel.Window['glass shatter']:Play()
		for i,v in pairs(doorModel.Window.Window:GetChildren()) do
			if v:IsA('BasePart') or v:IsA('UnionOperation') then
				v:Destroy()
			end
		end
		for i = 1, amountofshards do
			local clone = game.ReplicatedStorage.Shard:Clone()
			clone.Parent = workspace.Fx
			local Yscale = math.random(1,5)
			local Zscale = math.random(1,5)

			clone.Size = Vector3.new(0.05, Yscale, Zscale)

			clone.Position = doorModel.ShardsSpawn.Position
		--	game.ReplicatedStorage.Remotes.TextEffect:FireClient(plr, clone)
			game.Debris:AddItem(clone, 60)
			i += 1

		end
		for i,v in pairs(doorModel.Window.CrackedWindow:GetChildren()) do
			if v:IsA('BasePart') or v:IsA('UnionOperation') then
				v.Transparency = 0
			end
		end
		local CollectionService = game:GetService("CollectionService")
		for i,v in pairs(workspace.Fx:GetChildren())do
			if v.Name == "Shard" then
				CollectionService:AddTag(v, "Currency")
			end
		end
		plr.PlayerGui.MainGui.TextLabel.Text = tostring(tonumber(plr.PlayerGui.MainGui.TextLabel.Text) + amountofshards)
		plrenter:Fire(number)
	end
	wait(.1)
end
function door.new(roomModel, number, locked)
	local doorModel = workspace.Door:Clone()
		
	doorModel:PivotTo(roomModel.Exit.CFrame)
	doorModel:SetAttribute("Open", false)
	doorModel:SetAttribute("Locked", false)


	doorModel.WindowNumber.SurfaceGui.TextLabel.Text = string.format('%04d', number)
	if locked == true then
		doorModel:SetAttribute('Locked', true)
		doorModel.WoodBoard["Meshes/Planks_Cube.001"].ProximityPrompt.Enabled = true
		doorModel.WoodBoard2["Meshes/Planks_Cube.001"].ProximityPrompt.Enabled = true
		for i,v in pairs(doorModel.WoodBoard:GetChildren()) do
			if v:IsA('BasePart', 'UnionOperation') then
				v.Transparency = 0
				v.CanCollide = true
			end
		end
		for i,v in pairs(doorModel.WoodBoard2:GetChildren()) do
			if v:IsA('BasePart', 'UnionOperation') then
				v.Transparency = 0
				v.CanCollide = true
			end
		end
	end


	doorModel.WoodBoard["Meshes/Planks_Cube.001"].ProximityPrompt.PromptButtonHoldBegan:Connect(function(plr)
		if plr.Character:FindFirstChild('Crowbar') then
			doorModel.WoodBoard["Meshes/Planks_Cube.001"]["Destroying A Car Crowbar 5 (SFX)"]:Play()
			local hum = plr.Character:FindFirstChild('Humanoid')
			local track = hum.Animator:LoadAnimation(workspace.Items.Crowbar.Handle.Use)
			track.Looped = true	
			track:Play()
		end
	end)

	doorModel.WoodBoard["Meshes/Planks_Cube.001"].ProximityPrompt.PromptButtonHoldEnded:Connect(function(plr)
		doorModel.WoodBoard["Meshes/Planks_Cube.001"]["Destroying A Car Crowbar 5 (SFX)"]:Stop()
		local hum = plr.Character:FindFirstChild('Humanoid')
		for _,anim in pairs(hum.Animator:GetPlayingAnimationTracks()) do
			if anim.Name == "Use" then
				anim:Stop()
				break
			end
		end
	end)

	doorModel.WoodBoard2["Meshes/Planks_Cube.001"].ProximityPrompt.PromptButtonHoldBegan:Connect(function(plr)
		if plr.Character:FindFirstChild('Crowbar') then
			doorModel.WoodBoard2["Meshes/Planks_Cube.001"]["Destroying A Car Crowbar 5 (SFX)"]:Play()
			local hum = plr.Character:FindFirstChild('Humanoid')
			local track = hum.Animator:LoadAnimation(workspace.Items.Crowbar.Handle.Use)
			track.Looped = true
			track:Play()
		end
	end)

	doorModel.WoodBoard2["Meshes/Planks_Cube.001"].ProximityPrompt.PromptButtonHoldEnded:Connect(function(plr)
		doorModel.WoodBoard2["Meshes/Planks_Cube.001"]["Destroying A Car Crowbar 5 (SFX)"]:Stop()
		local hum = plr.Character:FindFirstChild('Humanoid')
		for _,anim in pairs(hum.Animator:GetPlayingAnimationTracks()) do
			if anim.Name == "Use" then
				anim:Stop()
				break
			end
		end

	end)

	doorModel.WoodBoard["Meshes/Planks_Cube.001"].ProximityPrompt.Triggered:Connect(function(plr)
		if plr.Character:FindFirstChild('Crowbar') then
			for i,v in pairs(doorModel.WoodBoard:GetChildren()) do
				if v:IsA('BasePart' or 'UnionOperation') then
					v.Anchored = false
					v.CanCollide = false
				end
			end
			doorModel.WoodBoard["Meshes/Planks_Cube.001"]["Wood break 1"]:Play()
			if doorModel:GetAttribute('Locked') == true then
				doorModel:SetAttribute('Locked', false) 
			end
			wait(1)

			doorModel.WoodBoard:Destroy()

			if not doorModel:FindFirstChild('WoodBoard2') then
				if plr.Character:FindFirstChild('Crowbar') then
					plr.Character:FindFirstChild('Crowbar'):Destroy() 
				elseif plr.Backpack:FindFirstChild('Crowbar') then
					plr.Backpack:FindFirstChild('Crowbar'):Destroy()
				end
			end
		end	

	end)

	doorModel.WoodBoard2["Meshes/Planks_Cube.001"].ProximityPrompt.Triggered:Connect(function(plr)
		if plr.Character:FindFirstChild('Crowbar') then
			for i,v in pairs(doorModel.WoodBoard2:GetChildren()) do
				if v:IsA('BasePart' or 'UnionOperation') then
					v.Anchored = false
					v.CanCollide = false
				end
			end
			doorModel.WoodBoard2["Meshes/Planks_Cube.001"]["Wood break 1"]:Play()
			if doorModel:GetAttribute('Locked') == true then
				doorModel:SetAttribute('Locked', false) 
			end
			wait(1)
			doorModel.WoodBoard2:Destroy()
			if not doorModel:FindFirstChild('WoodBoard') then
				if plr.Character:FindFirstChild('Crowbar') then
					plr.Character:FindFirstChild('Crowbar'):Destroy() 
				elseif plr.Backpack:FindFirstChild('Crowbar') then
					plr.Backpack:FindFirstChild('Crowbar'):Destroy()
				end
			end
		end
	end)



	doorModel.Hitbox.Touched:Connect(function(hit)
		if doorModel:GetAttribute('Open') == false and hit.Parent:IsA('Tool') and hit.Parent.Name ~= 'Crowbar' then
			local plr = game.Players:GetPlayerFromCharacter(hit.Parent.Parent)
			game.ReplicatedStorage.Remotes.WindowBreakAttack:FireClient(plr, locked)
			game.ReplicatedStorage.Remotes.WindowBreakAttack.OnServerEvent:Connect(function(player, var, lockedz)
	
				if var == true then
					
					if not lockedz then	
						door.open(doorModel, number, player, hit.Parent.Name)
					end
					if lockedz then
						if not doorModel:FindFirstChild('WoodBoard') and not doorModel:FindFirstChild('WoodBoard2') then
							door.open(doorModel, number, player,hit.Parent.Name)
						end
					end
				end
			end)
		end
		wait(.5)
	end) 
	local binable = Instance.new('BindableEvent')
	binable.Event:Connect(function()
		if doorModel:GetAttribute('Open') == false then
			if not locked then
				door.open(doorModel, number)
			end
		end
	end)
	binable.Name = 'OpenEvent'
	binable.Parent = doorModel


	doorModel.Parent = roomModel


	return doorModel
end



return door

Local Script:

local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local tool = script.Parent
local hold = tool:FindFirstChild('Hold')
local attack = tool:FindFirstChild('Attack')
local animationtrack = char:WaitForChild('Humanoid').Animator:LoadAnimation(hold)
local db = false
local cd = 2

tool.Equipped:Connect(function()
	animationtrack.Looped = true
	animationtrack:Play()
end)

tool.Unequipped:Connect(function()
	animationtrack:Stop()
end)

tool.Activated:Connect(function()
	if db == false then
		db = true
		local clone = game.ReplicatedStorage.SwordHitbox:Clone()
		script.Parent.Attacking.Value = true
		clone.Parent = tool
		clone.CanCollide = false
		clone.Anchored = false
		--clone.Transparency = 1
		clone.Massless = true
		local weld = Instance.new('WeldConstraint', tool.Handle)
		weld.Part0 = tool.Handle
		weld.Part1 = clone
		animationtrack:Stop()
		local animationattack = char:WaitForChild('Humanoid').Animator:LoadAnimation(attack)
		animationattack:Play()
		wait(0.78)

		tool["Sword Swing Metal Heavy"]:Play()

		animationattack.Stopped:Wait()
		clone:Destroy()
		weld:Destroy()
		script.Parent.Attacking.Value = false
		animationtrack:Play()
		wait(cd)
		db = false
	end
end)

game.ReplicatedStorage.Remotes.WindowBreakAttack.OnClientEvent:Connect(function(lockedz)
	local anim 
	local anims = char.Humanoid:GetPlayingAnimationTracks()
	for i, animation in pairs(anims) do
		if animation.Name == 'Attack' then
			anim = animation
		end
	end
	if anim then
		anim:GetMarkerReachedSignal("Attack"):Connect(function()
			game.ReplicatedStorage.Remotes.WindowBreakAttack:FireServer(script.Parent.Attacking.Value, lockedz)
			script.Parent.Attacking.Value = false
		end)
	end
end)

Video:https://streamable.com/69zawh

1 Like

Use the microprofiler to identify the source of the lag. It works best if you also profile/annotate your code with debug.profilebegin

1 Like

I have no idea how to use the microprofiler, but I added what you said to the code, and I checked the frame it showed there was lag, but I can’t seem to find the source. I attach a screenshot on what it showed.

Sorry for the later response by the way.

Those Giant Bars are likely the source of your lag, The bigger they are, means that it takes more time for the Computer (pretty sure?) to process them, which can lag the game.

@DasKairo is correct. The source of your lag is related to physics because all of those subtasks fall under the PhysicsStepped supertask. It has something to do with the glass breaking itself.

Won’t it still be fine because I got the game.Debris:AddItem in the code? Or is there any alternate solutions? Maybe the deletion time for the debris is too long?

As far as I am sure you are making the broken glass pieces transparent, although it may seem like they don’t render, they actually do; so make sure to either anchor them or just destroy them manually.

I don’t see where I made them transparent. Can you quote it please?

EDIT: You mean this

for i,v in pairs(doorModel.Window.Window:GetChildren()) do
			if v:IsA('BasePart') or v:IsA('UnionOperation') then
				v:Destroy()
			end
		end

My apologies, I read your code incorrectly. Sorry about that one! :sweat_smile:

Oh its all good, no worries! Maybe ill just change the deletion time for now.

Have you tried changing it before and checked if the lag occurs?
As nombreincorrectodepn said, you can also make them anchored after they have touched the ground so the object stops rendering.

I just made the deletion time faster and it seemed to work. Thanks for all your help!

1 Like

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