Attempt to index nil with 'GetMouseLocation'

Hey!

I’ve been working on a weapon system for fun, and want to make the player’s arms move up and down with the mouse. I am finding the mouse’s location through UserInputService as the mouse object is not entirely reliable. The tool is perfectly functional upon equipping it, but when I reequip it the output is bombarded with this:

The function below is used to find the mouse’s position and raycast to find its world position.

	playerInputService = game:GetService("UserInputService")

	local function GetMouseTarget(ignore)
		local mouseposition = playerInputService:GetMouseLocation() - GuiService:GetGuiInset()
		
		local unscaled_ray = workspace.CurrentCamera:ViewportPointToRay(mouseposition.X,mouseposition.Y)
		local result = workspace:Raycast(unscaled_ray.Origin, unscaled_ray.Direction*500)
		if result then
			return result.Position
		else
			return unscaled_ray.Origin + unscaled_ray.Direction*180
		end
	end

I am at a complete loss as to what is causing the error because playerInputService is not a nil value. Any help would be very much appreciated :,)

add a print statement right above it to validate, is it actually nil?

I tried that, but it didn’t print anything :confused:

	local playerInputService = game:GetService("UserInputService")

	local function GetMouseTarget(ignore)
playerInputService = game:GetService("UserInputService")
		mouseposition = playerInputService:GetMouseLocation() - GuiService:GetGuiInset()
		
		local unscaled_ray = workspace.CurrentCamera:ViewportPointToRay(mouseposition.X,mouseposition.Y)
		local result = workspace:Raycast(unscaled_ray.Origin, unscaled_ray.Direction*500)
		if result then
			return result.Position
		else
			return unscaled_ray.Origin + unscaled_ray.Direction*180
		end
	end

idk but worth a try ig LOO (i just went off this

I tried that too lol
So far I have tried:

  • Printing in various spots

  • Redefining playerInputService

  • Disconnecting the bind when the weapon is unequipped (no idea why just want it to work)

i didnt even see this till now, but this may be related idk

This is used to ignore roblox’s built in gui inset:

It already does that

Hey, for anyone looking back on this, I figured it out!
I made an if/then statement that checks for playerInputService before using the ‘GetMouseLocation’ function. I don’t really know why this worked, but it did and that’s good enough for me :slight_smile: