Clamping LookRotation angle

I have a turret that aims up and rotates on the Z-axis, using LookRotation to look at specific game objects. I tried to use my eulerAngles clamp that works for my player controlled turret that rotates on the same axis with mouse input using transform.Rotate. Here is the script:

       		Vector3 look = target.transform.position - transform.position;
	   		look.z = 0;
       		targetRotation = Quaternion.LookRotation (look);
       		transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);
			
			transform.eulerAngles = new Vector3(0, 0, Mathf.Clamp (transform.eulerAngles.z, CminAngle, CmaxAngle));

The Mathf.Clamp line just causes the turret to turn sideways and stay that way. Is clamping LookRotation not the same as clamping transform.Rotate?

Any eulerAngle you get is converted from a Quaternion. Any angle you set is converted to a Quaternion. The angle you set is not necessarily the same one you get back. For example execute this code:

transform.eulerAngles = new Vector3(180,0,0);
Debug.Log(transform.eulerAngles);

The value you will get back is (0,180,180), the same physical rotation, but a different Euler angle representation. So clamping your Euler angles will not work all the time. One way to fix your code is to instead test the angle of two Quaternions. Assuming your turret is pointed half way between the two max angles on start, you can do this (untested):

using UnityEngine;
using System.Collections;
 
public class Tracker : MonoBehaviour { 
	
	public Transform target;
	public float maxAngle = 35.0f;
	private Quaternion baseRotation;
	private Quaternion targetRotation;

	
	void Start() {
		baseRotation = transform.rotation;
	}
	
	void Update() {
		
		Vector3 look = target.transform.position - transform.position;
        look.z = 0;
		
        Quaternion q = Quaternion.LookRotation (look);
		if (Quaternion.Angle (q, baseRotation) <= maxAngle)
			targetRotation = q;
		
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 2.0f);
	}
}

You can use Vector3.Angle as well to monitor deviation from wished direction.

if(vector3.Angle(centrallook.vector,currentlook.vector)<45){rotate towards…);