object rotating x-axis and y-axis without rotating z-axis

I am tring to raote an object(let it be cube for example).If I rotate the object in y direction it is working properly.but if I rotate the object in x direction , the value of y and z are also changing.Problem is its rotating in z direction.But I dont need z.I tried a lot but cannot figure it out.I tried to put limitation for x rotation but its is not working and its rotating in z direction also…can anyone help with this issue.

function Update () {

transform.rotation.z=0;
Debug.Log(transform.rotation.x);

if(transform.rotation.x>=0 )
{
transform.rotation.x=0;
}

if(transform.rotation.x<=-60 )
{
transform.rotation.x=-60;

}
if(Input.GetKey(KeyCode.A))
{
Left();
}

if(Input.GetKey(KeyCode.S))
{
Right();
}
if(Input.GetKey(KeyCode.D))
{
UP();
}
if(Input.GetKey(KeyCode.F))
{
Down();
}

}

function Left()
{
transform.Rotate(0,9030Time.deltaTime,0);
}

function Right()
{
transform.Rotate(0,-9030Time.deltaTime,0);
}

function UP()
{
transform.Rotate(9020Time.deltaTime,0,0);
}

function Down()
{
transform.Rotate(-9020Time.deltaTime,0,0);
}

Another example tried…

using UnityEngine;

using System.Collections;

public class rotatenew : MonoBehaviour {

public float speed = 100f;

private Transform _tr = null;

private Vector2 _lastMousePosition = Vector2.zero;

// Use this for initialization

void Start () {

_tr = gameObject.transform;

}

// Update is called once per frame

void Update () {

Vector2 _currentMousePosition = (Vector2)Input.mousePosition;

Vector2 mouseDelta = _currentMousePosition - _lastMousePosition;

mouseDelta *= speed * Time.deltaTime;

_lastMousePosition = _currentMousePosition;

if(Input.GetMouseButton(0)){

_tr.Rotate(mouseDelta.y * -1f, mouseDelta.x * -1f, 0f, Space.World);

}

}

}

Does it have a RigidBody component? You can constraint rotation on any axis using the RigidBody.
This will prevent it from rotating from things like physics collisions, unless you specifically give it motion through a script.

It’s not really clear what you expect to happen, but you might want to add an extra “Space.World” parameter to your Y-axis Rotate calls - it will make the rotation get applied in world space, which might be what you want. See the documentation here for an example: