How to toggle Mouse Lock using scripts

You want to control the player’s ability to toggle mouse lock in game. Perhaps it messes up the torso during ragdoll, or conflicts with the camera during lerping. Here, I’ll show you a simple way how.

Using Player.DevEnableMouseLock, we need a LocalScript, Script, and a RemoteEvent.

Client

Here, we repeatedly set the mouse lock off and on in a loop.

local replicatedStorage = game:GetService("ReplicatedStorage")
local SetMouseLock = replicatedStorage.SetMouseLock -- rename your RemoteEvent

while true do
	SetMouseLock:FireServer(false) -- disable mouse lock
	task.wait(2)
	SetMouseLock:FireServer(true) -- enable mouse lock
	task.wait(2)
end

Server

We set the DevMouseLockEnabled property on the server since we cannot do that on the client.

local replicatedStorage = game:GetService("ReplicatedStorage")
local SetMouseLock = replicatedStorage.SetMouseLock -- rename your RemoteEvent

SetMouseLock.OnServerEvent:Connect(function(player, enabled: boolean?)
	if typeof(enabled) ~= "boolean" then return end
	player.DevEnableMouseLock = enabled
	print(`set MouseLock to {enabled}`)
end)

Result

Mouse lock now swaps between toggleable and not toggleabble every 2 seconds.


You can also turn this into a module if need be.

Hope this helps.

2 Likes