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

Mouse.Target Troubles (?)

Asked by 8 years ago

So I'm currently Experimenting with the Mouse and I've run into a bit of an error

Apologies if it's a bit hard to understand my question.

(LocalScript) :

local Player = game.Players.LocalPlayer

local Mouse = Player:GetMouse()


function TestMouse  ()



    local Distance = (Mouse.Target.Position.magnitude - Player.Character.Torso.Position.magnitude)--Line 13



    if Mouse.Target == nil then        
        print ("Not an Object;nil")



    elseif Distance <= 10 and Mouse.Target ~= nil then

        Mouse.Target.BrickColor = BrickColor.new("Bright red")

        print ("Succesfully Changed BrickColor to Bright red")




        elseif Distance >10 and Mouse.Target ~= nil then

        print ("Distance = "..Distance)
    end



end


Mouse.Button1Down:connect(TestMouse)

Basically whenever I try to click somewhere on the Skybox it doesn't print : "Not an Object;nil"

and gives me this error :

Players.Player.PlayerGui.MouseTest:13: attempt to index field 'Target' (a nil value)

The LocalScript works perfectly unless I click somewhere on the Skybox

1
It's because you're trying to calculate Distance before checking if the mouse's target is nil or not. DevSean 270 — 8y

2 answers

Log in to vote
2
Answered by 8 years ago

What happens if you look at the sky?

You're not checking to see if Target exists before indexing on it. If you're pointing your mouse into infinity, your mouse's target is nothing. And as a result, you can't logically assume that Target is anything but nil. Put an if statement to escape if that is the case.

0
Man so many people unhappy with my answers today. If there's something you're unhappy with, tell me. User#6546 35 — 8y
0
Oh no my bad,I just forgot to Accept the Answer :P creatorstorm 8 — 8y
0
Thank you by the way. creatorstorm 8 — 8y
0
No there was somebody who downvoted my answer, and the same happened in one of my previous answers. Given that I normally get these right, I didn't see any reason for there to be a silent downvote. User#6546 35 — 8y
0
Oh alright. creatorstorm 8 — 8y
Ad
Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
8 years ago
local Distance = (Mouse.Target.Position.magnitude - Player.Character.Torso.Position.magnitude)

if Mouse.Target == nil then

Just to clarify a bit on Satire's answer, you do check if it's nil, but you do so after you already use it!

That doesn't make a lot of sense, and is the reason why you get the error on line 10 (or 13 originally). Remember, scripts always read your code in order, left to right, top to bottom.

You can fix this simply by putting everything you do to the target (like line 10) inside the if statement, so you know that the target exists before you use it.

0
Thank you also! :D creatorstorm 8 — 8y

Answer this question