Touched script causes lag

So i made a portal after completing a level in my game to advance to the next level…

But it causes a lot of lag and i don’t know why

script.Parent.Touched:Connect(function(hit)
	print("E")
	local player = game.Players:GetPlayerFromCharacter(hit.Parent)
	if player then
		local In = player.leaderstats.InLevel
		if In ~= 0 then
			local h = hit.Parent.Humanoid
			local Color = player:WaitForChild("color")
			local HL = hit.Parent.Highlight
			Color.Value = "none"
			HL.Enabled = false
			print("e")
			local HumanoidRootPart = hit.Parent:FindFirstChild("HumanoidRootPart")
			if HumanoidRootPart then
				HumanoidRootPart.CFrame = SpawnL.CFrame + Vector3.new(0,5,0)
			end
			local LevelVal = player.leaderstats.completed

			if LevelVal.Value == 0 then
				print("1")
				EndLevel:Fire(player, In.Value)
				print("E")

			end
			In.Value = 0
			return
		end
		


	end
end)




1 Like

If this line is running multiple times, it may be causing the lag spike. How are the prints behaving? Try to use a debounce to prevent unnecessary code from executing.

local Debounces = { }

script.Parent.Touched:Connect(function(hit)
	print("E")
	local player = game.Players:GetPlayerFromCharacter(hit.Parent)
	if player then
		if Debounces[player] then return end
		local In = player.leaderstats.InLevel
		if In ~= 0 then
			Debounces[player] = true
			task.delay(5, function()
				Debounces[player] = nil
			end)
			
			local h = hit.Parent.Humanoid
			local Color = player:WaitForChild("color")
			local HL = hit.Parent.Highlight
			Color.Value = "none"
			HL.Enabled = false
			print("e")
			local HumanoidRootPart = hit.Parent:FindFirstChild("HumanoidRootPart")
			if HumanoidRootPart then
				HumanoidRootPart.CFrame = SpawnL.CFrame + Vector3.new(0,5,0)
			end
			local LevelVal = player.leaderstats.completed

			if LevelVal.Value == 0 then
				print("1")
				EndLevel:Fire(player, In.Value)
				print("E")

			end
			In.Value = 0
			return
		end



	end
end)
1 Like

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