Flashlight beam not being positioned correctly

I am working on a volumetric lighting plug-in, and I have made it so a beam comes out of a flashlight. I have scripted it so the beam can get obstructed by parts, and what not. What happens is occasionally… one of the attachments will be positioned at Vector3.new(0, 0, 0). Here is a video of me explaining everything:

What should be happening is, if the beam is obstructed, then position the end of the beam at the position where the raycast hit (We do this check every frame).

Here is a model of the flashlight that contains the script:

Here is the localscript that that does the “Beam Obstruction” detection:

local parent = script.Parent
local flashLightDistance = 20
local equipped = false
local light = script.Parent:WaitForChild("Light")
local lightAttachment = parent:WaitForChild("LightEnd"):WaitForChild("Attachment1")
local vector = 'RightVector'

function lighting()
	
	while equipped do
		game:GetService("RunService").RenderStepped:Wait()
		local ray = Ray.new(light.Position, light.CFrame[vector] * flashLightDistance)
		local hit, pos = workspace:FindPartOnRay(ray)
		
		if not hit then
			lightAttachment.WorldPosition = light.CFrame[vector] * flashLightDistance
		else
			lightAttachment.WorldPosition = pos
		end
	end
end

parent.Equipped:Connect(function()
	equipped = true
	lighting()
end)

parent.Unequipped:Connect(function()
	equipped = false
end)

Can someone please tell me how I can fix this bug / keep this from happening?

I happened to discover the fix. Here is the fixed code:

local parent = script.Parent
local flashLightDistance = 20
local equipped = false
local light = script.Parent:WaitForChild("Light")
local lightAttachment = parent:WaitForChild("LightEnd"):WaitForChild("Attachment1")
local vector = 'RightVector'

function lighting()
	
	while equipped do
		game:GetService("RunService").RenderStepped:Wait()
		local ray = Ray.new(light.Position, light.CFrame[vector] * flashLightDistance)
		local hit, pos = workspace:FindPartOnRayWithIgnoreList(ray, {parent})
		
		lightAttachment.WorldPosition = pos
	end
end

parent.Equipped:Connect(function()
	equipped = true
	lighting()
end)

parent.Unequipped:Connect(function()
	equipped = false
end)