My objective is to fire an event when these two conditions are met:
When the player is near a specific object
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?
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.