Rotation of object

I am trying to rotate an object inside another object and limit how much it can but I can’t seem to get it to work. I have even tried with mathf.clamp but it doesn’t seem to work the closes I got is this.

if (Input.GetKey (KeyCode.A))
{
if(transform.rotation.z >= 0.0)
{
transform.Rotate(Vector3.back * Time.deltaTime * Speed);
}
}
if (Input.GetKey (KeyCode.D))
{
if(transform.rotation.z <= 20.0)
{
transform.Rotate(Vector3.forward * Time.deltaTime * Speed);
}
}

You have two basic problems. 1) You are lost in the concept of a Quaternion (i.e. rotation) and 2) lost in the euler that makes up a reference to the Quaternion.

A Quaternion is a set of 4 numbers that make up a rotation in 3d sense. So transform.z, may not be what you are thinking it is. What you are really looking for is the Euler.

Next, you need to understand that an euler is a representation of the rotation, not the rotation. They define the rotation in X, Z then Y rotation in world space. What you can get is the Z euler and compare it to your numbers. Then comes the next problem. Eulers are written in 0 to 360, so when you hit anything below zero, it bumps up to 360 and starts down from there. To fix this, you need to adjust the number as needed.

The cool part is this is already written in a ClampAngle statement that was written for the standard mouse orbit.

Here it is:

static function ClampAngle (angle : float, min : float, max : float) {
	if (angle < -360)
		angle += 360;
	if (angle > 360)
		angle -= 360;
	return Mathf.Clamp (angle, min, max);
}

The cool part is, if you feed it negative numbers, euler will simply move them where they are supposed to be.

Play with it, test it and see what you come up with.

Perhaps iTween might help. I generally leave all my rotations to that. Saves me a lot of headaches.