Clamping Camera doesn't work

I’m trying to clamp my camera’s rotation on the x axis, but when it goes down to 0, it snaps back to 45. Here is the portion of the script that clamps the camera. Here is the script:

   Vector3 rot = transform.eulerAngles;
    rot.z = 0;
    if (rot.x > 45f) {
    	rot.x = 45f;
    }
    if (rot.x < -45f) {
    	rot.x = -45f;
    }
    transform.eulerAngles = rot;

This behavior happens because, no matter what, the value of transform.eulerAngles.x will never be negative when you get it from the scene since the engine works with floats from 0 to 360 when it comes to angles (so your -45 becomes 315). Even when you manually assign a vector with negative components to it, it’s gonna get converted back to the [0, 359[ before the next frame.

Your reflex of trying with 315 was half the solution, but you also have to manually check if the angle is over 180 (negative) or under 180 (positive), since values from 0 to 45 are also smaller than 315.

The following changes to your code snippet should solve your problem:

Vector3 rot = transform.eulerAngles;
rot.z = 0;
if (rot.x > 45f && rot.x < 180f){
     rot.x = 45f;
}
else if (rot.x > 180f && rot.x < 315f){
     rot.x = -45f;
}
transform.eulerAngles = rot;