I am trying to execute a remote event from a local script when the player sees an AI, using a box attached to the AI character to detect rays:

The script works if the AI is stood out in the open with no walls, however if there is a wall behind it, the raycast does not return “seen”
Here is the script:
local partToCheck = workspace:GetDescendants()
local camera = workspace.CurrentCamera
local replicated = game:GetService("ReplicatedStorage")
local event = replicated:WaitForChild("Seen")
local function seen(player)
for i, v in pairs(workspace:GetDescendants()) do
if v.Name == "hitbox" then
local partToCheck = v
local vector, inViewport = camera:WorldToViewportPoint(partToCheck.Position)
local onScreen = inViewport and vector.Z > 0
-- Raycast outward:
local ray = camera:ViewportPointToRay(vector.X, vector.Y, 0)
local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
raycastParams.FilterDescendantsInstances = {partToCheck, game.Players.LocalPlayer.Character}
local raycastResult = workspace:Raycast(ray.Origin, ray.Direction * 10000, raycastParams)
-- Final check:
local isVisible = onScreen and not raycastResult
if isVisible then
event:FireServer()
print("seen")
end
end
end
end
while wait(0.2) do
local seen = seen()
if seen then
seen()
end
end