If statement giving error instead of moving on

I’ve got a raycast script that checks for a parent on the FindPartOnRayWithIgnoreList. The problem that I have is that when it can’t find a parent it just gives me the error of “attempt to index nil with ‘Parent’”. Anyone able to help?

script.Parent.Event.OnServerEvent:Connect(function(player, mousePos)
	script.Parent.Chamber.Muzzle["FlashFX[Flash]"].Enabled = true
	
	local tool = script.Parent
	local user
	local Ignore = {player.Character, tool}

	local ray = Ray.new(tool.Chamber.Muzzle.CFrame.p, (mousePos - tool.Chamber.Muzzle.CFrame.p).unit*300)
	local hit, position = game.Workspace:FindPartOnRayWithIgnoreList(ray, Ignore)
	
	if hit.Parent then
		local humanoid = hit.Parent:FindFirstChild("Humanoid") or hit.Parent.Parent:FindFirstChild("Humanoid")
		
		if humanoid and hit.Parent.Name ~= player.Name then
			humanoid:TakeDamage(7)
		end
	end

	wait(0.2)
	
	script.Parent.Chamber.Muzzle["FlashFX[Flash]"].Enabled = false
end)

first check if it even hit anything by putting
if hit and hit.Parent then

1 Like