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

What is this mouse.Target bug?

I have a simple function within a script that goes as follows:

mouse.Button2Down:connect(function()
	if on and mouse.Target:findFirstChild("Runner") then
		mouse.Target:Remove()
	end
end)

Yet every once in a while the Output tells me there was an error because mouse.Target didn't exist. I can't consistently reproduce the problem and I don't know why it happens. I even tried adding "and mouse.Target" to the if statement and I still got the error. It's like it's removing it before the if statement passes or something. Any ideas?

1 answer

mouse.Target can become nil.

If you point your mouse at the sky for example, mouse.Target is nil. A very simple fix would be an if statement that checks if mouse.Target ~= nil.

--Local Script
mouse.Button2Down:connect(function()
	if mouse.Target then
		if on and mouse.Target:FindFirstChild("Runner") then
			mouse.Target:Remove()
		end
	end
end)

You could also set the mouse Target as a variable,

--Local Script
mouse.Button2Down:connect(function()
	local Target = mouse.Target
	if Target then
		if on and Target:FindFirstChild("Runner") then
			Target:Remove()
		end
	end
end)

Few More Optional Changes

You're using Remove() as opposed to Destroy(). If you're not trying to re-access, or bring back, the Target, I would suggest using the Destroy function, as it's more efficient.

Here's a link to an article about this that's really interesting and goes into much more detail about this.

Here would be the final script,

--Local Script
mouse.Button2Down:connect(function()
	local Target = mouse.Target
	if Target then
		if on and Target:FindFirstChild("Runner") then
			Target:Destroy()
		end
	end
end)

I hope I helped.

Good Luck!

If I helped, don't forget to hit the accept button!

1 comment

1

+1 for pointing out that :Remove() is deprecated.

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