Mouse-controlled camera getting stuck.

I’m a total noob to unity, and I was trying to get a rudimentary mouse-controlled camera. I have some basic code, and looking horizontally and vertically is fine. However, when I’m looking around the z-rotation of the camera changes, rotating the view weirdly, and when I turn around so the rotation around the y-axis is 180, I can’t look horizontally or vertically, it gets locked and if I try to look away it only affects the z-axis rotation, which shouldn’t be changed in the first place. Here’s my script in the main camera:

var xdirection : float = 0.0;
var ydirection : float = 0.0;
var cenw : float = Screen.Width/2;
var cenh : float = Screen.Height/2;
function Update () {
	var mousex : float = Input.GetAxis("Mouse X");
	var mousey : float = Input.GetAxis("Mouse Y");
	
	if (mousex != Screen.width/2 && mousey != Screen.height/2) {
		xdirection += (mousex*0.4)- cenw*Time.deltaTime;
		ydirection -= (mousey*0.4)-cenh*Time.deltaTime;
	}
	else {
		xdirection = 0;
		ydirection = 0;
	}
	
	xdirection = Mathf.Clamp(xdirection,-90,90);
	ydirection = Mathf.Clamp(ydirection,-90,90);
	
	transform.rotation.x = ydirection;
	transform.rotation.y = xdirection;
	
	Screen.lockCursor = true;
}

The main camera has a rigidbody and a capsule collider. I’ve tested it without both components and I get the same issues. “cenw” and “cenh” are the x and y coords for the center of the screen.

Rotation in Unity is a Quaternion. For setting rotation directly use quaternion functions. For example

transform.rotataion = Quaternion.Euler(xdir, ydir, transform.rotation.eulerAngles.z);