Get last seen position when target behind wall

So im using a state machine for my NPC. It Starts off patroling and in the patrol state it checks what this code returns. Which in this case is the target transform. Then it transitions into the chase state where the the agent target is set to what the same function returns. What i want to do is check when the player goes behind a wall and get its last position so i can trigger the search state. I’ve tried making this myself but to no avail.

        public Transform GetTarget()
        {
            Collider[] targetsInViewRadius = Physics.OverlapSphere(transform.position, viewRadius, targetMask);

            for (int i = 0; i < targetsInViewRadius.Length; i++)
            {
                Transform target1 = targetsInViewRadius*.transform;*

Vector3 dirToTarget = (target1.position - transform.position).normalized;

if (Vector3.Angle(transform.forward, dirToTarget) < viewAngle / 2)
{
float distanceToTarget = Vector3.Distance(transform.position, target1.transform.position);

RaycastHit hit;
if (Physics.Raycast(transform.position, dirToTarget, out hit, distanceToTarget, targetMask))
{
target = hit.transform;

return target;
}
}
}
return null;
}

Does it make sense to make it part of this function?
Your NPC can have a transform lastKnownTransform.

In case your NPC receives a null return value, he can check upon that lastKnownTransform position and see if he returns into the patrol state.