Camera lock on script that stays with player.

So I am building a third person adventure game where I have a lock on script that I have attached to the main camera. The script works fine but when I hit the “lock” button the camera will automatically snap to any game object tagged as “Enemy”. The problem is that if the player keeps moving around they will run right out of the scree and it will stay locked onto the target. Attached is my script any pointers would be greatly appreciated. Thank you in advance.

public class TargetLockON : MonoBehaviour
{
public GameObject target;
public Camera CAM;
private void Start()
{
CAM = GetComponent();
target = GameObject.FindWithTag(“Enemy”);
}
private void Update()
{
LockOn();

}
void LockOn()
{
if(Input.GetButton(“Target”))
{
transform.LookAt(GameObject.FindWithTag(“Enemy”).transform);
}
}
}

Please use code tags (see first post in forum) to make your code readable.

I’m not sure what you want. Do you want the camera to stop locking on when the target gets far enough away? You can take the distance to the target and if it gets larger than a certain amount, disable or destroy this script.