Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why does Mouse.Target return nil?

Asked by 8 years ago

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

Log in to vote
1
Answered by 8 years ago

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)
0
Oh, I see. Didn't know it worked like that. Thanks! AwsomeSpongebob 350 — 8y
Ad
Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
8 years ago

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
You made an error on line 5 within the code. :) TheeDeathCaster 2368 — 8y
0
Thanks for pointing that out, fixed. Goulstem 8144 — 8y

Answer this question