How do i improve E to interact code

i want to improve the code by many ways

local DriveSeats = {}

local Player = game.Players.LocalPlayer
local HumanoidRootPart = Player.Character:WaitForChild('HumanoidRootPart')
local UIS = game:GetService('UserInputService')
local RunService = game:GetService('RunService')
local Range = 8

local function FindSeat()
	for _,v in pairs(workspace:GetDescendants()) do
		if v:IsA('VehicleSeat') then
			table.insert(DriveSeats, v)
		end
	end
end


FindSeat()


UIS.InputBegan:Connect(function(Input, gameProcessedEvent)
	if gameProcessedEvent then return end
	if Input.KeyCode == Enum.KeyCode.E or Input.KeyCode == Enum.KeyCode.ButtonY then
		for _,v in pairs(DriveSeats) do
			local Distance = (v.Position - HumanoidRootPart.Position).Magnitude
			if Distance <= Range and v.Occupant == nil then
				game.ReplicatedStorage.SitEvent:FireServer(v)
			end
		end
	end
end)




RunService.RenderStepped:Connect(function()
	for _,v in pairs(DriveSeats) do
		local Distance = (v.Position - HumanoidRootPart.Position).Magnitude
		if Distance <= Range and v.Occupant == nil then
			game.ReplicatedStorage:WaitForChild('NextBtn').Parent = v
		else
				if v:FindFirstChild('NextBtn') then
					v.NextBtn.Parent = game.ReplicatedStorage
			 end
		end
	end
end)



I would probably use Context Action service instead of User Input Service. I find it way better for input handling.

Check it out here: ContextActionService | Documentation - Roblox Creator Hub

2 Likes

To me the code looks just fine, it’s simple and easy to fix if there ever is a problem.

1 Like