My Code that Works on an object's rotation doesn't work.

I’m coding a system, where if my 3d object moves forward, it’s rotation goes down to a certain point, when I try my code, it will keep rotating for ever when I use it (pressing W)…

if (Input.GetKey(KeyCode.W))
    transform.Translate(0f, 0f, speed * Time.deltaTime); // Forward movement of the player's character.

    if (transform.rotation.x <= 20) //If the rotation of the object is below or = 20, make the rotation higher
        transform.Rotate(rotationSpeedWhileMoving * Time.deltaTime, 0f, 0f);
else if (transform.rotation.x > 0) //Returns THe object's rotation to 0
    transform.Rotate(-1 * rotationBackwardsSpeed * Time.deltaTime, 0f, 0f);

transform.rotation is a QUATERNION, you should not try to read and write values of it, unless you really know what you are doing, and it clearly seems that it’s not the case.

You should check against transform.localEulerAngles instead, which are the values displayed in the inspector:

if (transform.localEulerAngles.y <= 20)
// ...
if (transform.localEulerAngles.x > 0)

Good day.

As @Hellium says, in Unity, standard variable for rotation are QUATERNION (there are not the “typical” 3 rotation of each axis). In the inspector, you see the EULER ROTATION (not quaternion), so if you want to manipulate rotation, you should do it via Euler angles (they are indeed the 3 axis rotation from 0 to 360).

You should check against



Go try it, and if don’t suceed, come again!