'How to limit rotation of object in unity

I want to stop rotation of my camera once it reaches 90 degrees on the x as well as when it reaches -90 degrees on the x. cam is the camera, the lines that actually deal with the camera are the ones at the bottom. Not sure what else stack overflow wants me to add.

Script

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

public class cameracontroller : MonoBehaviour
{
    public float speed = 50f;

    public GameObject cam;

    Rigidbody player_rb;
    float player_speed;
    float player_reversespeed;

    void Start()
    {
        player_rb = GetComponent<Rigidbody>();
        player_speed = 4.0f;
        player_reversespeed = 2f;
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKey(KeyCode.W))
        {
            player_rb.velocity = transform.forward * player_speed;
        }

        if(Input.GetKey(KeyCode.S))
        {
            player_rb.velocity = -transform.forward * player_reversespeed;
        }

        if(Input.GetKey(KeyCode.A))
        {
            transform.Rotate(0, -Time.deltaTime * speed,  0, Space.Self);
        }

        if(Input.GetKey(KeyCode.D))
        {
            transform.Rotate(0, Time.deltaTime * speed,  0, Space.Self);
        }

        //camera up/down

        if(Input.GetKey(KeyCode.UpArrow))
        {
            cam.transform.Rotate(-Time.deltaTime * speed, 0, 0, Space.Self);
        }

        if(Input.GetKey(KeyCode.DownArrow))
        {
            cam.transform.Rotate(Time.deltaTime * speed, 0, 0, Space.Self);
        }
    }
}


Solution 1:[1]

Usually a simple Mathf.Clamp(val, -90, 90) would seem to be sufficient, but Unity's euler rotation is of range (0, 360). What I usually would do is something like this:

private static bool IsInRange(float rotVal)
{
    return Mathf.Clamp((val > 180 ? val - 360 : val), -90, 90);
}

This was the rotation value is going to be of range (-180, 180).

Then I'd check if the change I'm about to do to the object's rotation is going to exceed that range:

if(Input.GetKey(KeyCode.A))
{
    var change = -Time.deltaTime * speed;

    if(IsInRange(obj.eulerAngles.y + change))
    {
        transform.Rotate(0, change,  0, Space.Self);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 slowikowskiarkadiusz