Attempt to index nil with "Hit"

So i’m making a gun raycast thing, and i have this error: Attempt to index nil with “Hit”.
Client code:

local Tool = script.Parent
local FireGun = Tool:WaitForChild("FireGun")

Tool.Activated:Connect(function()
	FireGun:FireServer(Tool)
end)

Server code:

local Tool = script.Parent
local FireGun = Tool:WaitForChild("FireGun")
FireGun.OnServerEvent:Connect(function(Player)
	local Mouse = Player:GetMouse()
	local ray = workspace:Raycast(Tool.MuzzlePart, Mouse.Hit.LookVector * 2000)
	if ray.Instance then print(ray.Instance:GetFullName()) end
end)

You can’t get the Mouse from server scripts, you need to get the Hit position from the client and pass that in as a parameter

@HugeCoolboy2007 has also mentioned another point that should be noted, you never use the Tool that was fired as you made a variable it for it, so why fire it anyways?

local Tool = script.Parent
local FireGun = Tool:WaitForChild("FireGun")
local Player = game:GetService("Players").LocalPlayer
local Mouse = Player:GetMouse()

Tool.Activated:Connect(function()
	FireGun:FireServer(Mouse.Hit.LookVector)
end)
local Tool = script.Parent
local FireGun = Tool:WaitForChild("FireGun")
FireGun.OnServerEvent:Connect(function(Player,lookVector)
	local ray = workspace:Raycast(Tool.MuzzlePart.Position, lookVector * 2000)
	if ray.Instance then print(ray.Instance:GetFullName()) end
end)
2 Likes

In addition to what @EmbatTheHybrid said, after examining your code, why do you send a Tool as a parameter but never use it in the event connection?

2 Likes

Tool.MuzzlePart is mentioned, the origin is the muzzle part, and the direction is Hit.LookVector * 2000 (the range).
Also, i’m going to implement a config module later on

Nvm, i put muzzlepart instead of muzzlepart.postion

Change it to how I edited my first post

1 Like