How do I detect when a player pressed E and is near an object efficiently?

My objective is to fire an event when these two conditions are met:

  1. When the player is near a specific object
  2. When the player pressed the key

This is my code as of now:

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()

local RemoteEvent = game:GetService("ReplicatedStorage").Interact
local UIS = game:GetService("UserInputService")

local Dist = 20

local function GetInteractParts()
	for i, Descendants in pairs(workspace:GetDescendants()) do
		if Descendants.Name == "Interact" then
			return Descendants
		end
	end
end


UIS.InputBegan:Connect(function(Input, GameProcessed)
	if (GetInteractParts().Position - Character.HumanoidRootPart.Position).Magnitude < Dist
		and Input.UserInputType == Enum.UserInputType.Keyboard then
		
		print("in bounds")
		if Input.KeyCode == Enum.KeyCode.E then
			print("activate")
			RemoteEvent:FireServer(GetInteractParts())
		end
		
	end	
end)

The problem I have is that it lags if the player is within those bounds. I’m not too sure what causes it. Is there a better way of scripting this all together?

You are looping through the entire workspace? That might have caused the lag, maybe try putting it in a folder to loop through less stuff.

Also this happens every input began so yeah it’s going to cause lag.

Edit: to try improve I believe this has been done before, so try looking at this already solved post for clues.

There’s even a tutorial on it wow

2 Likes

I have already thought of this. But in the longrun, wouldn’t it be difficult to organise with so many interactable parts?

Well there are other ways to organize your parts like using the Collection services to tag your parts with interactability E option. So maybe you can use a script to do the organizing for you but that’s a different story.

Edit: What I mean is that you can perform an :IsA() check or a string name check to see if a part you want is interactable.

example if a workspace part :IsA(“VehicleSeat”) then you add it to the collection services tag. That sort of thing.

1 Like