unity – How to make an arrow / marker point to the offscreen object in 3D space?

I’m trying to create an off screen indicator. An arrow that would move around the screen to point to the target in 3D space.

Something like this:

enter image description here

I wrote this script, but the problem is that it doesn’t really work properly.

The arrow moves around the screen, but if let’s say the target is behind the player the arrow should point to the bottom of the screen, but instead it’s located somewhere in the upper corner.

using UnityEngine;
using UnityEngine.UI;

public class Pointer : MonoBehaviour
{
    (Header("Graphics"))

    (SerializeField) Image pointer = null;
    (SerializeField) Transform target = null;

    (Header("Parameters"))

    (SerializeField) bool rotateToTarget = false;

    private float northDir = 0f;
    private new Camera camera;

    private void Start()
    {
        camera = Camera.main;
    }

    private void Update()
    {
        Rotate();
    }
    private void Rotate()
    {
        float minX = pointer.GetPixelAdjustedRect().width / 2f;
        float maxX = Screen.width - minX;

        float minY = pointer.GetPixelAdjustedRect().height / 2f;
        float maxY = Screen.height - minY;

        var pos = camera.WorldToScreenPoint(target.position);

        if (Vector3.Dot(target.position - camera.transform.position, camera.transform.forward) < 0)
        {
            if (pos.x < Screen.width / 2f)
            {
                pos.x = maxX;
            }
            else
            {
                pos.x = minY;
            }
            if (rotateToTarget)
            {
                northDir = target.eulerAngles.y;
                pointer.rectTransform.localEulerAngles = new Vector3(pointer.rectTransform.localEulerAngles.x, pointer.rectTransform.localEulerAngles.y, -northDir);
            }
        }
        pos.x = Mathf.Clamp(pos.x, minX, maxX);
        pos.y = Mathf.Clamp(pos.y, minY, maxY);

        pointer.transform.position = pos;
    }
}