Auto Aiming System

hi everyone

I have a probleme, I want to add an auto aiming system on my project, it's a TPS.

When I press a button, the nearest enemie is targeted by the player.

I use Cinemachine and CM FreeLook for the camera system.

I beginning with a friend to write a script for implement this, but i have so many bugs and i need help for ending this.

This is my code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AutoAim : MonoBehaviour
{
    public LayerMask EnemyLayer;
    public float FieldOfView;
    public Transform CameraLookAt;
    private Vector3 originalPosition;
    public Cinemachine.CinemachineFreeLook playerCamera;
    private float yAxis;
    private float xAxis;



    void Start()
    {
        originalPosition = CameraLookAt.position;
    }

    void Update()
    {
        if (Input.GetButtonDown("AutoAim"))
        {
            Collider[] targetCols = Physics.OverlapSphere(transform.position, 10, EnemyLayer);

            List<Transform> targetTransforms = new List<Transform>();
            for (int i = 0; i < targetCols.Length; i++)
            {
                Vector3 direction = targetCols[i].transform.position - transform.position;
                if (Vector3.Angle(transform.forward, direction) < FieldOfView / 2)
                {
                    targetTransforms.Add(targetCols[i].transform);
                }
            }
            Debug.Log("visible enemies: " + targetTransforms.Count);

            playerCamera.m_XAxis.Value = xAxis;
            playerCamera.m_YAxis.Value = yAxis;

            var enemy = targetTransforms[0];
            var directionToEnemy = enemy.position - transform.position;
            var directionPlayerForward = transform.forward;
            directionToEnemy.y = 0;
            directionPlayerForward.y = 0;
            var angle = Vector3.Angle(directionPlayerForward, directionToEnemy);
            playerCamera.m_YAxis.Value = angle;

        }

    }
}

We have choose to take the X and Y value of the CM Free Look, but i have so many problem.
The enemy is not aiming and my character look at to another way.

Well , first of your approach is pretty heavy, specially calling it in the "update" loop nonstop,

you should first add an "if" statement waiting for the button to get pressed,
then you dont get the closest enemy, you just choose the first enemy found in your list

var enemy = targetTransforms[0];

that wont work,
you should get obv. all enemys in range but also get the closest range enemy, not just the first element found