UserInputService is not working

hello,

I have a problem with UserInputService, after pressing “E” nothing happens, but when I press the left mouse button and then “E”, the script works. Why?

Script:

local plr = game.Players.LocalPlayer
local Mouse = plr:GetMouse()
local UIS = game:GetService("UserInputService")

local GuiActive = false
local PlanetClimed = false
local PlanetSelected

function OnMoved()
	
	if Mouse.Target ~= nil and Mouse.Target.Parent == workspace.Planets then
		GuiActive = true
		Mouse.Target.InfoGui.Enabled = true
		PlanetSelected = Mouse.Target
	else
		if GuiActive == true then
			GuiActive = false
			PlanetSelected = nil
			for _,v in pairs(workspace.Planets:GetChildren()) do
				v.InfoGui.Enabled = false
			end
		end
	end
end

function InputBegan(Input)
	
	if PlanetClimed then return end
	
	if Input.KeyCode == Enum.KeyCode.E and PlanetSelected ~= nil then
		PlanetClimed = true
		game.ReplicatedStorage.Remote.ClimPlanet:FireServer(PlanetClimed)
	end
		
	
end

Mouse.Move:Connect(OnMoved)
UIS.InputBegan:Connect(InputBegan)

Well you didn’t assign a value to PlanetSelected when you first defined it, meaning it will be nil until you move your mouse and activate your OnMoved() function so assuming the click is the first time you move your mouse that would be why

If that doesn’t do it can you explain more in detail? It’s hard to know exactly what your situation is.

I already know if there was a problem, but thanks for the help