Lag when pressing E

So I made an Interaction system but whenever I press the Key meant to interact even if I’m not hovering over an interaction part the game’s fps drops like crazy for a few seconds. I would appreciate if anyone can help me.

Here is my script used to do the Interactions

local CollectionService = game:GetService("CollectionService")
local UIS = game:GetService("UserInputService")
local mouse = game.Players.LocalPlayer:GetMouse()
local player = game.Players.LocalPlayer
local character = player.CharacterAdded:Wait()


while wait(0.1) do
	if CollectionService:HasTag(mouse.Target, "Interactable") and (character.HumanoidRootPart.Position - mouse.Target.Position).Magnitude <= 6 then
		local Interaction = require(mouse.Target.Interaction)
		local description = Interaction.GetDescription()
		player.PlayerGui.ScreenGui.Key.Visible = true
		player.PlayerGui.ScreenGui.Key.Description.Text = description
		UIS.InputBegan:Connect(function(input)
			if input.KeyCode == Enum.KeyCode.E and CollectionService:HasTag(mouse.Target, "Interactable") then
				Interaction.Interact()
			end
		end)
	else
		player.PlayerGui.ScreenGui.Key.Visible = false
	end
	
end

Edit: It only seems to happen when the game has been running for a bit, also it only happens when I’m interacting now.

Have you tried using proximity prompt?

Yes, but proximity prompts just don’t seem right for what I’m working on.

1 Like

Probably because it’s looped in a while wait() do. It’ll keep doing UIS.InputBegan each time it runs through the loop. If the loop goes through 10 times, pressing E will run 10 times. I hope this makes sense, if it helps let me know!

1 Like

And you are constantly making this Connect event over and over and over and over, basically every time your condition is true for the if CollectionService:HasTag. You probably have a memory leak from it as well.
I think it would be best to separate out the UIS.InputBegan:Connect from the while loop, so it is created only the once and add your magnitude checks in the if, which when true make the Gui visible.
I think. If it was me doing it.