How to lock mouse and then unlock it using the same button

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

local IsXpressed = false

userInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.X then
		if IsXpressed == false then
			IsXpressed = true
			RunService.RenderStepped:Connect(function()
				userInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
				
			end)
		elseif IsXpressed == true then
			IsXpressed = false
			RunService.RenderStepped:Connect(function()
				userInputService.MouseBehavior = Enum.MouseBehavior.Default
				
			end)
		end
	
	end

end)

I tried making my mouse locked and then unlocked by using the X button to toggle it. When i press X once mouse successfully becomes locked, when i press it a second time nothing happens and it doesn’t go back to default

Any solutions?

The problem would be these. Add some if then checks to see if the IsXPressed variable is false or true

local RunService = game:GetService("RunService")

local IsXpressed = false

userInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.X then
		if IsXpressed == false then
			IsXpressed = true
			RunService.RenderStepped:Connect(function()
				if IsXPressed then 
					userInputService.MouseBehavior = Enum.MouseBehavior.LockCenter
				end
			end)
		elseif IsXpressed == true then
			IsXpressed = false
			RunService.RenderStepped:Connect(function()
				if not IsXPressed then
					userInputService.MouseBehavior = Enum.MouseBehavior.Default
				end
			end)
		end
	end
end)

He already checked that if the IsXpressed variable is false or not

Yes, but what he is using is a loop. This continues even if you press X again causing it to switch between Default and LockCenter behaviors. You need to check inside of the loop so it doesn’t change it if it isn’t true/false.

2 Likes

Yup your right, i remember you also helped me back on something else, so thanks for helping me once again lol

Okay so I guess it’s fixed now lol

yup, but you also tried helping me lol, so thank you as well

1 Like

Yeah, I’m happy to help, I believe what I helped on last time was deleting a default face lol

yup, that was definitely the one

1 Like