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

Mouse.Target Troubles (?)

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 comment

1

It's because you're trying to calculate Distance before checking if the mouse's target is nil or not.

2 answers

✓ Accepted answer

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.

5 comments

0

Man so many people unhappy with my answers today. If there's something you're unhappy with, tell me.

0

Oh no my bad,I just forgot to Accept the Answer :P

0

Thank you by the way.

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.

0

Oh alright.

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.

1 comment

0

Thank you also! :D

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