How to set limits to the rotation of an object with the mouse?


I am newbie using Unity and I have a problem that is how to establish some parameters or limits in the rotation of an object and even the same camera with the mouse.

My current code is:

transform.Rotate((Input.GetAxis("Mouse Y") * speed * Time.deltaTime), (Input.GetAxis("Mouse X") * speed * Time.deltaTime), 0, Space.World);

The problem with this code is that it rotates the object, but if a limit, ie the object can rotate 180 degrees or up to 360 degrees and what I want or look for is to rotate with a limit of 160 degrees or less, because what I seek is to be able to create a hand weapon which will remain in the front, but it will be able to rotate to aim at the target, without it turning over backwards or fence to one side and cross the character

Thanks and sorry for my english.

Try checking if your rotation + new rotation is on your limit, something like this:

 float X = Input.GetAxis("Mouse X") * speed * Time.deltaTime;
        float Y = Input.GetAxis("Mouse Y") * speed * Time.deltaTime;
        float limitRotationX = 160;
        float limitRotationY = 160;

        if (transform.eulerAngles.x + X < limitRotationX)
            transform.Rotate(X, 0, 0);
        if (transform.eulerAngles.y + Y < limitRotationX)
            transform.Rotate(0, Y, 0);

Find and improve my solution which is:

	public float sensitivity = 10f;
	public float maxYAngle = 80f;
	private Vector2 currentRotation;

	void Update () {
		currentRotation.x += Input.GetAxis("Mouse X") * sensitivity;
		currentRotation.y -= Input.GetAxis("Mouse Y") * sensitivity;
		currentRotation.x = Mathf.Clamp(currentRotation.x, -maxYAngle, maxYAngle);
		currentRotation.y = Mathf.Clamp(currentRotation.y, -maxYAngle, maxYAngle);
		transform.rotation = Quaternion.Euler(currentRotation.y,currentRotation.x,0);
		if (Input.GetMouseButtonDown(0))
			Cursor.lockState = CursorLockMode.Locked;


The solution to my problem I found it in: FREE MOUSE ROTATING CAMERA - Questions & Answers - Unity Discussions