limiting rotation of a rigidbody in C#

so… I have been fighting with this for a while. I am new to unity so please excuess my complete ignorance.

this is a “space” flying game. simple, no gravity.
The controls work the way I want them to because I have a script that I found and suited to my needs, works great except I want to limit the “roll” of my object say between 45 degrees and -45 degrees.

I thought the line “Mathf.Clamp(AddRot.z,-45,45);” would solve it but my limited understanding is hindering me.

I think it is because the rotation works between 0 and 360, but I am not sure how to tell my object that it can only rotate between 45 and 315.

Heck I am probably completely off my rocker and using it incorrectly and in the wrong place.

please help.
this is what my flyscript.cs looks like.

using UnityEngine;
using System.Collections;

public class flyscript : MonoBehaviour {
	// Use this for initialization
	void Start () {

	}
	
	// Update is called once per frame
    public float AmbientSpeed = 100.0f;

    public float RotationSpeed = 200.0f;
	

	void Update()
    {        
		Quaternion AddRot = Quaternion.identity;
        float roll = 0;
        float pitch = 0;
        float yaw = 0;

		roll = Input.GetAxis("roll") * (Time.deltaTime * RotationSpeed);
		pitch = Input.GetAxis("pitch") * (Time.deltaTime * RotationSpeed);
        yaw = Input.GetAxis("yaw") * (Time.deltaTime * RotationSpeed);
		AddRot.eulerAngles = new Vector3(-pitch, yaw, -roll);
		Mathf.Clamp(AddRot.z,-45,45);
		rigidbody.rotation *= AddRot;
		Vector3 AddPos = Vector3.forward;
        AddPos = rigidbody.rotation * AddPos;
        rigidbody.velocity = AddPos * (Time.deltaTime * AmbientSpeed);
    }
}

Dude - can you simply use Rotate

it is unbelievably simple to use. You should very rarely be fooling with the underlying angles.

As a student, you should also study and experiment with

which is incredibly useful. You have to understand the concept of the “rotation axis” to use it, which is exactly what you have to learn here.

I think your problem is that you are multiplying your “AddRot” value (which is essentially a deltaRotation) after you’ve clamped it, when you need to clamp it AFTER the addition of the rotation. Cuz as it is, it’s clamping, then multiplying the AddRot with the -45 and the 45.

//	    Mathf.Clamp(AddRot.z,-45,45);
	    rigidbody.rotation *= AddRot;
		
		if(transform.localRotation.z < -45)
			transform.localRotation.z = -45;
		else if(transform.localRotation.z > 45)
			transform.localRotation.z = 45;

As Fattie said, you should use Transform.Rotate to rotate your object, instead of messing with its euler angles.

However, your code is not working as expected because your are not clamping your rotation value, because your are not assigning it.

You need to assign the result of Mathf.Clamp(AddRot.z,-45,45) somewhere and apply it.