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
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.
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.