So I am trying to make a small script that checks if whatever the player’s pointing at is a par or a meshpart, however the problem occurs when I attempt to use Mouse.Target, as the error is always "Attempt to index “nil” on line 6 of the following code:
local debounce = true
local Player = script.Parent.Parent.Parent
local Mouse = Player:GetMouse()
script.Parent.Activated:Connect(function()
if debounce == true then
if Mouse.Target:IsA("MeshPart") or Mouse.Target:IsA("Part") then
print("Valid target")
end
end
end)
The script is parented to a tool which is parented into starterpack. I tried printing the “Player” variable and confirmed that it was indeed the player.
I have no clue what to do or why Mouse.Target is nil, and that’s why I come forth seeking help.
local debounce = true
local Player = script.Parent.Parent.Parent
local Mouse = Player:GetMouse()
script.Parent.Activated:Connect(function()
if debounce == true then
if Mouse.Target:IsA("MeshPart") or Mouse.Target:IsA("BasePart") then
print("Valid target")
end
end
end)
If you need a check to happen constantly, consider writing something like this:
local Equipped = false
local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()
script.Parent.Equipped:Connect(function()
Equipped = true
end)
script.Parent.Unequipped:Connect(function()
Equipped = false
end)
game:GetService("RunService").RenderStepped:Connect(function()
if Equipped == true then
if Mouse.Target:IsA("MeshPart") or Mouse.Target:IsA("BasePart") then
print("Valid target")
end
end
end)
Is that a server script or a localscript?
You can’t get the player’s mouse from a server script, GetMouse() will just return nil. Maybe that’s your issue?
An example solution would be to make a localscript fire a remote upon Activated, which would send the player’s Mouse.Target to the server, and then the server script would be able to use it.
OP’s problem could’ve meant 2 things, Attempt to index nil with IsA or Attempt to index nil with Target, judging by how Kiriot’s post got the solution, it’s likely it was the latter
@Mihnealihnea I still recommend what I had done in my code by checking the Target exists because even though Kiriot fixed your error, it can still error again if you look at the sky
Well, I really should have paid more attention/or specified that. In other words, this is the solution: I made it a server-side script accidentally, and that’s why it kept returning nil no matter what. Thank you!
Also since there seems to be some discussion about the error, here’s a snippet showing it in full detail: