Light Detection Script Not Working

Hello, I’m trying to make a script that will detect if a part is in a shadow or not.

when I place the part close to the light source, it works fine. When it’s 10 studs studs away, it gives an error.

I’ve tried looking on the DevForum to see if other people have had the same problem.

Is there a way to fix this error? Or is there a more efficient way to achieve my end goal.

here are some photos of the bug:


local lights = game.Workspace.Lights:GetChildren()
local RayOrgin = script.Parent.Position
for i = 1, #lights do
	local child = lights[i]
	if child.PointLight.Range > (child.position - script.Parent.Position).Magnitude then
		print("Close")
		print((child.position - script.Parent.Position).Magnitude)
		local RayDirection = child.Position
		print(child.Position)
		local RayParams = RaycastParams.new()
		RayParams.FilterDescendantsInstances = {script.Parent}
		RayParams.FilterType = Enum.RaycastFilterType.Blacklist
		local raycastResult = workspace:Raycast(RayOrgin, RayDirection, RayParams)
		local HitPart = raycastResult.Instance
		if HitPart.Name == lights[i].Name then
			print("on")
			script.Parent.BrickColor = BrickColor.new("Bright green")
		else 
			print("Off")
			script.Parent.BrickColor = BrickColor.new("Really red")
		end
	else
		print("Far")
		script.Parent.BrickColor = BrickColor.new("Really red")
		print((child.position - script.Parent.Position).Magnitude)
	end
end

Add a check to see whether or not raycastResult.Instance is nil.
That should eliminate the error.