How to write a mouse input code?

I am a beginner in scripting and I want to find out how to write a mouse input code.

I have been attempting to write a code for mouse inputs, but it does not seem to work.

I have tried some other codes for mouse inputs, but they didn’t seem to work either. Although I probably messed something up on them probably.

These are the codes I’ve been attempting:

local player = game:GetService("UserInputService")
local mouse = player:MouseEnabled()
mouse.Button1Down:Connect(function()
	print("pressed")
end)
--Code number 2:
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
mouse.Button1Down:Connect(function()
	print("pressed")
end)

On the 1st code, it says that ‘MouseEnabled’ is not a valid member of ‘UserInputService’
When I tested the second code, it said that ‘player’ was a nil value.

I have considered using ‘GetMouseDelta()’, but I’m clueless to what it does.
All help is appreciated.

Code number 2 is more accurate. It should work on a local script.

1 Like

The first code will fail because I believe your mouse returning method doesn’t exist. You are also setting the UserInputService as a variable called player when it isn’t a player instance – it’s a service.

The second code is right, it just needs to be in a localscript which should be in somewhere like StarterGui.

1 Like

Both LocalPlayer and mouse cannot be accessed from the server. These objects work only in LocalScript.

1 Like

The code is written inside a LocalScript and I’ve also tested it out insdie StarterPlayer and StarterGUI, however, it still repeats the same error message:
ServerScriptService.hiiri:2: attempt to index local ‘player’ (a nil value)

Well that script is either unrelated or shouldn’t be in ServerScriptService – this is code2 right?

Nevermind, I’m an idiot. I was looking at the wrong script :D.

The api-reference is your friend here, it returns a Vector2 holding the delta movement of the mouse only if it’s locked (via MouseBehavior property).

1 Like