Help with User Input

Greetings my fellow devs,
Recently I ran into a problem with a script I created. The script should set a variable to true and another one to false when “V” is pressed, and then set them back to their original values when “V” is pressed again.

Here is the script:


--Services
local UIS = game:GetService("UserInputService")

--Variables 
local plr = game.Players.LocalPlayer
local chr = plr.Character
local humanoid = chr.Humanoid
local camera = workspace.CurrentCamera
local right = true
local left = false
local mouse = plr:GetMouse()

--Preset Values
camera.FieldOfView = 50
humanoid.CameraOffset = Vector3.new(1, 0, 0)

--Functions


mouse.KeyDown:Connect(function(Key) 
	if Key == "v" then
		if right == true and left == false then
			right = false 
			left = true
			print("left is true!")
		end	
	end  
end)

mouse.KeyDown:Connect(function(Key)
	if Key == "v" then
		if right == false and left == true then
			right = true 
			left = false
			print("right is true!")
		end	
	end
end)

I’ve tried using User Input Service, but it didn’t work either. Any suggestions?

This is what I get at the output, it prints them together:

1 Like

U cant do two functions that are looking for the same key, basically what is happening is that the second function returns the change to its original form. What to do? - u need to use debounce and only one function

So, if I understood correctly, you are telling me that what I want to archive is possible, but the way I do it is wrong, so I have to use debounce, right?

mouse.KeyDown:Connect(function(Key) 
	if Key == "v" then
		if right == true and left == false then
			right = false 
			left = true
			print("left is true!")
      else
            right = true
            left = false
		end	
	end  
end)

Sorry for weird formation, I am on phone

1 Like

Thanks @nuttela_for1me for the solution, it was just what I needed!!!

1 Like

mouse.KeyDown is deprecated… UIS and CAC are way more reliable; that is not good practice. detect input like so:

local uis = game:GetService("UserInputService")

uis.InputBegan:Connect(function(key, chat) -- when input has began connect a function with arguements, the 1st arguement will be used to detect the key and the 2nd arguement is the game proccessed event, but we use it for making the key not activate while chatting
   if chat then return end -- if the game didnt process then end
   if key == Enum.KeyCode.V then
      if right == true and left == false then
        right = false
        left = true
        print("left is".. left)
      else
        right = true
        left = false
        print("right is"..right)
      end
   end
end
2 Likes

Thanks a lot for the reply!
I would just like to know if this (function(inputObject, gameProssecedEvent) is the same as (function(key, chat). Could you please tell me, because I am very confused with arguments.
Thanks a lot!

yeah it is, i just use what i actually use it as for the arguements names

1 Like