Is there any way you can optimize this further? maybe a way to make it so it only uses one billboardgui at a time so its not constantly writing to so many billboardguis

and please prevent bugs like the billboardgui glitching out and not appearing


local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local PlayerGui = LocalPlayer:WaitForChild("PlayerGui")

local BindingsFolder = PlayerGui:FindFirstChild("Bindings") or (function()
	local Folder = Instance.new("Folder")
	Folder.Name = "Bindings"
	Folder.Parent = PlayerGui
	return Folder
end)()

local BillboardTemplate = PlayerGui:WaitForChild("Keybind", 100)

local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")
local TweenService = game:GetService("TweenService")

local KeybindService = {}
KeybindService.Registry = {}
KeybindService.ActiveTweens = {}
KeybindService.CurrentlyVisibleByKeyCode = {}

local SquareRoot = math.sqrt
local FrameBudget = 1/60 * 0.5

local function AnimateClick(UserInterfaceScaleInstance)
	local DownTween = TweenService:Create(UserInterfaceScaleInstance, TweenInfo.new(0.1, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Scale = 0.9 })
	local UpTween = TweenService:Create(UserInterfaceScaleInstance, TweenInfo.new(0.1, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Scale = 1 })
	DownTween:Play()
	DownTween.Completed:Once(function()
		UpTween:Play()
	end)
end

local function GetDistanceSquared(PositionOne, PositionTwo)
	local DeltaX = PositionOne.X - PositionTwo.X
	local DeltaY = PositionOne.Y - PositionTwo.Y
	local DeltaZ = PositionOne.Z - PositionTwo.Z
	return DeltaX*DeltaX + DeltaY*DeltaY + DeltaZ*DeltaZ
end

local function TriggerKeybind(PartInstance, Binding)
	local Character = LocalPlayer.Character
	local HumanoidRootPart = Character and Character:FindFirstChild("HumanoidRootPart")
	if HumanoidRootPart then
		local DistanceSquared = GetDistanceSquared(PartInstance.Position, HumanoidRootPart.Position)
		if DistanceSquared <= Binding.MaxDistanceSquared then
			Binding.Callback(PartInstance)
			AnimateClick(Binding.UserInterfaceScaleInstance)
		end
	end
end

UserInputService.InputBegan:Connect(function(Input, GameProcessed)
	if GameProcessed then return end

	local Character = LocalPlayer.Character
	local HumanoidRootPart = Character and Character:FindFirstChild("HumanoidRootPart")
	if not HumanoidRootPart then return end

	local HumanoidRootPartPosition = HumanoidRootPart.Position
	local NearestByKeyCode = {}

	for PartInstance, Binding in pairs(KeybindService.Registry) do
		if Input.KeyCode == Binding.KeyCode then
			local DistanceSquared = GetDistanceSquared(PartInstance.Position, HumanoidRootPartPosition)

			local ExistingEntry = NearestByKeyCode[Binding.KeyCode]
			if not ExistingEntry or DistanceSquared < ExistingEntry.DistanceSquared then
				NearestByKeyCode[Binding.KeyCode] = {
					PartInstance = PartInstance,
					Binding = Binding,
					DistanceSquared = DistanceSquared
				}
			end
		end
	end

	for _, Data in pairs(NearestByKeyCode) do
		if Data.DistanceSquared <= Data.Binding.MaxDistanceSquared then
			TriggerKeybind(Data.PartInstance, Data.Binding)
		end
	end
end)

local UpdateIndex = 1
local RegistryArray = {}
local RegistryCount = 0

local function RebuildRegistryArray()
	RegistryArray = {}
	RegistryCount = 0
	for Part, Binding in pairs(KeybindService.Registry) do
		RegistryCount = RegistryCount + 1
		RegistryArray[RegistryCount] = {Part = Part, Binding = Binding}
	end
end

local RegistryDirty = true

RunService.Heartbeat:Connect(function()
	local StartTime = tick()

	local Character = LocalPlayer.Character
	local HumanoidRootPart = Character and Character:FindFirstChild("HumanoidRootPart")
	if not HumanoidRootPart then return end

	local HumanoidRootPartPosition = HumanoidRootPart.Position

	if RegistryDirty then
		RebuildRegistryArray()
		RegistryDirty = false
	end

	local NearestByKeyCode = {}

	local PartsPerFrame = math.max(10, math.ceil(RegistryCount / 4))
	local EndIndex = math.min(UpdateIndex + PartsPerFrame - 1, RegistryCount)

	for Index = UpdateIndex, EndIndex do
		if tick() - StartTime > FrameBudget then break end

		local Entry = RegistryArray[Index]
		if Entry then
			local Part = Entry.Part
			local Binding = Entry.Binding

			local RoughDistance = (Part.Position - HumanoidRootPartPosition).Magnitude
			if RoughDistance > Binding.MaxDistance * 1.5 then
				if Binding.BillboardGuiClone.Enabled then
					Binding.BillboardGuiClone.Enabled = false
				end
			else
				local DistanceSquared = GetDistanceSquared(Part.Position, HumanoidRootPartPosition)

				if DistanceSquared <= Binding.MaxDistanceSquared then
					local ExistingEntry = NearestByKeyCode[Binding.KeyCode]
					if not ExistingEntry or DistanceSquared < ExistingEntry.DistanceSquared then
						NearestByKeyCode[Binding.KeyCode] = {
							Part = Part,
							Binding = Binding,
							DistanceSquared = DistanceSquared
						}
					end
				end
			end
		end
	end

	for KeyCode, Data in pairs(NearestByKeyCode) do
		local CurrentlyVisible = KeybindService.CurrentlyVisibleByKeyCode[KeyCode]

		if CurrentlyVisible and CurrentlyVisible ~= Data.Part then
			local OldBinding = KeybindService.Registry[CurrentlyVisible]
			if OldBinding then
				local OldGuiClone = OldBinding.BillboardGuiClone
				if OldGuiClone.Enabled then
					if KeybindService.ActiveTweens[OldGuiClone] then
						KeybindService.ActiveTweens[OldGuiClone]:Cancel()
					end

					local HideTween = TweenService:Create(OldBinding.UserInterfaceScaleInstance, OldBinding.TweenInfo, { Scale = 0 })
					KeybindService.ActiveTweens[OldGuiClone] = HideTween

					HideTween:Play()
					HideTween.Completed:Once(function()
						OldGuiClone.Enabled = false
						KeybindService.ActiveTweens[OldGuiClone] = nil
					end)
				end
			end
		end

		local Binding = Data.Binding
		local GuiClone = Binding.BillboardGuiClone

		if not GuiClone.Enabled then
			GuiClone.Enabled = true
			GuiClone.Adornee = Data.Part

			if KeybindService.ActiveTweens[GuiClone] then
				KeybindService.ActiveTweens[GuiClone]:Cancel()
				KeybindService.ActiveTweens[GuiClone] = nil
			end

			Binding.UserInterfaceScaleInstance.Scale = 0
			local ShowTween = TweenService:Create(Binding.UserInterfaceScaleInstance, Binding.TweenInfo, { Scale = 1 })
			ShowTween:Play()
		end

		KeybindService.CurrentlyVisibleByKeyCode[KeyCode] = Data.Part
	end

	for KeyCode, VisiblePart in pairs(KeybindService.CurrentlyVisibleByKeyCode) do
		if not NearestByKeyCode[KeyCode] then
			local Binding = KeybindService.Registry[VisiblePart]
			if Binding then
				local GuiClone = Binding.BillboardGuiClone
				if GuiClone.Enabled then
					if KeybindService.ActiveTweens[GuiClone] then
						KeybindService.ActiveTweens[GuiClone]:Cancel()
					end

					local HideTween = TweenService:Create(Binding.UserInterfaceScaleInstance, Binding.TweenInfo, { Scale = 0 })
					KeybindService.ActiveTweens[GuiClone] = HideTween

					HideTween:Play()
					HideTween.Completed:Once(function()
						GuiClone.Enabled = false
						KeybindService.ActiveTweens[GuiClone] = nil
					end)
				end
			end
			KeybindService.CurrentlyVisibleByKeyCode[KeyCode] = nil
		end
	end

	UpdateIndex = UpdateIndex + PartsPerFrame
	if UpdateIndex > RegistryCount then
		UpdateIndex = 1
	end
end)

function KeybindService:Bind(PartInstance, KeyCode, Callback, Options)
	Options = Options or {}

	local MinDistance = Options.MinDistance or 0
	local MaxDistance = Options.MaxDistance or 20
	local TweenDuration = Options.TweenDuration or 0.2
	local Label = Options.Label or "[Error]"

	local TweenInfoObject = TweenInfo.new(TweenDuration, Enum.EasingStyle.Quad, Enum.EasingDirection.Out)

	local GuiClone = BillboardTemplate:Clone()
	GuiClone.Enabled = false
	GuiClone.Parent = BindingsFolder
	GuiClone.Key.Reason.Text = Label

	local UserInterfaceScaleInstance = GuiClone:FindFirstChildWhichIsA("UIScale", true)
	if UserInterfaceScaleInstance then
		UserInterfaceScaleInstance.Scale = 0
	end

	local KeybindButton = GuiClone:WaitForChild("Key")
	if KeybindButton then
		KeybindButton.MouseButton1Click:Connect(function()
			local Binding = KeybindService.Registry[PartInstance]
			if Binding then
				TriggerKeybind(PartInstance, Binding)
			end
		end)
	end

	if not PartInstance then return end

	KeybindService.Registry[PartInstance] = {
		KeyCode = KeyCode,
		Callback = Callback,
		MinDistance = MinDistance,
		MaxDistance = MaxDistance,
		MaxDistanceSquared = MaxDistance * MaxDistance,
		TweenInfo = TweenInfoObject,
		BillboardGuiClone = GuiClone,
		UserInterfaceScaleInstance = UserInterfaceScaleInstance,
	}

	RegistryDirty = true

	PartInstance.AncestryChanged:Once(function(_, Parent)
		if not Parent then
			self:Unbind(PartInstance)
		end
	end)
end

function KeybindService:Unbind(PartInstance)
	local Binding = KeybindService.Registry[PartInstance]
	if Binding then
		local GuiClone = Binding.BillboardGuiClone
		if KeybindService.ActiveTweens[GuiClone] then
			KeybindService.ActiveTweens[GuiClone]:Cancel()
			KeybindService.ActiveTweens[GuiClone] = nil
		end

		for KeyCode, VisiblePart in pairs(KeybindService.CurrentlyVisibleByKeyCode) do
			if VisiblePart == PartInstance then
				KeybindService.CurrentlyVisibleByKeyCode[KeyCode] = nil
				break
			end
		end

		GuiClone:Destroy()
		KeybindService.Registry[PartInstance] = nil
		RegistryDirty = true
	end
end

return KeybindService