Off screen indicator 3d

My code works fine but when I change the camera angle it doesn’t appear properly.
How do I fix this?

using UnityEngine;
using UnityEngine.UI;

public class OffScreenIndicator : MonoBehaviour
    // The target to follow
    public Transform target;

    // The camera that renders the scene
    public Camera cam;

    // The image that shows the indicator
    public Image image;

    // The margin of the indicator from the screen edge
    public float margin = 10f;

    // The position of the indicator on the screen
    private Vector2 position;

    // The width and height of the screen
    private float screenWidth;
    private float screenHeight;

    // The rect transform of the image
    private RectTransform rectTransform;

    void Start()
        // Get the rect transform of the image
        rectTransform = image.GetComponent<RectTransform>();

        // Get the width and height of the screen
        screenWidth = Screen.width;
        screenHeight = Screen.height;

    void Update()
        // Check if the target is on screen or not
        Vector3 screenPoint = cam.WorldToViewportPoint(target.position);

        bool onScreen = screenPoint.z > 0 && screenPoint.x > 0 && screenPoint.x < 1 && screenPoint.y > 0 && screenPoint.y < 1;

        // If the target is on screen, disable the image and return
        if (onScreen)
            image.enabled = false;

        // If the target is off screen, enable the image and calculate its position and angle
        image.enabled = true;

        // Convert the target's world position to screen position
        Vector3 screenPosition = cam.WorldToScreenPoint(target.position);

        // Clamp the position of the indicator to the screen edge
        position.x = Mathf.Clamp(screenPosition.x, margin, screenWidth - margin);
        position.y = Mathf.Clamp(screenPosition.y, margin, screenHeight - margin);

        // Set the position and rotation of the image
        rectTransform.position = position;


This post was flagged by the community and is temporarily hidden.