How do I make my raycast visuallizer not break?

You can write your topic however you want, but you need to answer these questions:

  1. I achieve to make a visualizer for my raycast.

  2. At where the distance variable is called, It says whenever you shoot at a nil object (like the sky) it “attempts to index nil with ‘position’”

  3. I’ve been looking at AI pages and searching for more articles but couldn’t find anything.

local tool = script.Parent
	local raycastParams = RaycastParams.new()
	raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
	raycastParams.FilterDescendantsInstances = {Client.Character, workspace.air}
	raycastParams.IgnoreWater = true
	local raycastResult = workspace:Raycast(tool.Handle.CFrame.p, (MousePosition - tool.Handle.CFrame.p).unit*9999999999, raycastParams)

	if raycastResult then
		local hitPart = raycastResult.Instance
		if hitPart.Parent:FindFirstChild("Humanoid") then
			print("hit")
			hitPart.Parent:FindFirstChild("Humanoid"):TakeDamage(35)
		end
	end
		
	local distance = (raycastResult.Position - tool.Handle.CFrame.p).magnitude
	local rayPart = Instance.new("Part", workspace)
	rayPart.Name          = "Visualizer"
	rayPart.BrickColor    = BrickColor.new("Brick yellow")
	rayPart.Transparency  = 0
	rayPart.CastShadow    = false
	rayPart.Anchored      = true
	rayPart.CanCollide    = false
	rayPart.TopSurface    = Enum.SurfaceType.Smooth
	rayPart.BottomSurface = Enum.SurfaceType.Smooth
	rayPart.formFactor    = Enum.FormFactor.Custom
	rayPart.Size          = Vector3.new(0.2, 0.2, distance)
	rayPart.CFrame        = CFrame.new(raycastResult.Position, tool.Handle.CFrame.p) * CFrame.new(0, 0, -distance/2)
	game:GetService("Debris"):AddItem(rayPart, .05)

When you shoot at the sky the raycastResult will become nil since the ray didn’t hit anything and so resulted in nil. To fix this you add an additional if statement for this scenario to find where the ray ended.

local hitPosition
if raycastResult then
 hitPosition = raycastResult.Position
else
--find where the ray ended
hitPosition = tool.Handle.CFrame.p+ (MousePosition - tool.Handle.CFrame.p).unit*9999999999
end

local distance = (hitPosition - tool.Handle.CFrame.p).magnitude