Mouse.Target not working 100% of the time

Hi there,
for a game I am working on there is a mechanic that involves clicking on an asset, followed by an action. To trigger this script, I am using Mouse.Target. This works kinda, sometimes it does and sometimes it doesn’t. The script will return nil when it doesn’t while I am very clearly clicking on one of the assets (print(mouse.Target.Name) prints nil). Obviously this has to be fixed for a game to work properly, but what should I do instead? Should I use raycasting with userinputservice? Perhaps a clickdetector? Or is there any way to optimize the functionality of Mouse.Target? Please leave your recommendations down below, thanks for reading.

Here is the script

--// Variables
wait(1)
local pickaxe = script.Parent

local plr = game.Players.LocalPlayer

local mouse = plr:GetMouse()

[...]

local db = false

--// Script
local function activated()
	print("Tool activated")
	if db == false then
		db = true
		if cooldown.Value == false then
			cooldownEvent:FireServer(plr)
			[...]
			
			if mouse.Target then
				print(mouse.Target.Name)
				if mouse.Target.Name == "Hitbox" then
					local hitbox = mouse.Target
					[...]
			
		        end
			end
		end
		db = false
	end
	print("End Swinghandler")
end

pickaxe.Activated:Connect(activated)```
1 Like

I thought it was print(Mouse.Target.Name) haven’t used that in awhile tho.

updated the post, thanks

30

Are you intending to click on one asset

Im not sure what you mean. The problem is that mouse.Target sometimes returns nil when it shouldnt. So yeah, I am intending to click on the asset

Can you post + format a script?

Added the important parts of the script

Could someone help me?

30

You’re using an older mouse, which is strongly discouraged from use. I would recommend you use something like ScreenPointToRay to the mouse position. ( API Documentation: Camera:ScreenPointToRay )

1 Like

Its not deprecated, still works perfectly fine.
Mouse (roblox.com)

“It remains supported because of its widespread use, but you should strongly consider using these alternatives.”

With that being said, it doesn’t mean its perfect, but you shouldn’t go around throwing improper information.

1 Like

Whoops! My bad, I must have recalled it wrong. I’ll edit my post now. Thanks for pointing that out!

With that said, I still would recommend my originally proposed solution.

1 Like