Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why does Mouse.Target return nil?

So what I want to do is get the Position/Name/Properties of the object my mouse is looking at. For testing purposes, I made function that would >print(MTarget) upon left clicking. However, it returns nil. When I try MTarget.Name, it gives me an error saying 'Could not index upvalue MTarget' or something.

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
local MTarget = Mouse.Target
Mouse.Button1Down:connect(function(MTarget)
	print(MTarget)
end)

No idea what the problem is. Any help is greatly appreciated. Lemme know if you've got any questions. Thanks! :)

2 answers

✓ Accepted answer

The thing with Mouse properties is they change (depending on the user's input, of course). Which means every time an event like this is fired, you need the most up-to-date value that corresponds with the property you're indexing.

In your case, you've created a variable name that represents a constant value (it won't change). So every time you're clicking the mouse, it's printing the same value you gave it when the program first ran.

Another thing you should also note, is the "Target" value you're looking for Isn't passed as an argument in the function you return to the "Button1Down" event. You can just index "Target" from the mouse every time the mouse is clicked. Try this example:

local Player = game:GetService'Players'.LocalPlayer
local Mouse = Player:GetMouse()

Mouse.Button1Down:connect(function()
	local Target = Mouse.Target
	if Target then
		print("Target: "..tostring(Target).." exists.")
	end
end)

1 comment

0

Oh, I see. Didn't know it worked like that. Thanks!

Your Problem

The Button1Down event does not return the mouse's target, it doesn't return anything. So since you re-defined the MTarget variable on line 5 and the event returns nil then when you print the variable it is going to print nil.

You already have the mouse defined, so just index the Target Property. But remember to define the MTarget variable inside the event.


Code

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()

Mouse.Button1Down:connect(function()
	local MTarget = Mouse.Target
	print(MTarget)
end)

2 comments

2

You made an error on line 5 within the code. :)

0

Thanks for pointing that out, fixed.

This discussion is preserved as it was. New answers, comments, and votes are closed.