Simple cube rotation script isn't working

I cropped out a bit of code to make this easier to read. Basically, I have a random variable (ourdir) which is either 1 or 2 and it determines if the cube’s X axis is rotated positively or negatively. The initial rotation is 90, 0, 180. I was using transform.rotate but it was giving me the same result, so that’s why I switched to this other rotation method. ourdir == 2 works fine, but ourdir == 1 has the cube kind of sitting in place. It jerks around a bit, but for some reason I’m unable to add to the X rotation of the model.

            currotation = transform.eulerAngles.x;
            anotherint = Random.Range(0.3f, 1.5f);

            if (ourdir == 1)
            {
                currotation = currotation + anotherint;
                transform.eulerAngles = new Vector3(currotation, 0, 180);
            }

            if (ourdir == 2)
            {
                currotation = currotation - anotherint;
                transform.eulerAngles = new Vector3(currotation, 0, 180);
            }

Unity stores transform rotations as a structure called a Quaternion. (For good reasons; go google if you care,)

When you access the eulerAngles.x portion of that, it produces essentially a “lossy” version of what the euler angle is from the contents of the quaternion, but a value suitable for seeing its rotation.

When you modify it (here by a fairly small amount, only 0.3 to 1.5 degrees), you are reassigning it into the .eulerAngles, which then “takes it the other way,” and creates a new Quaternion object to hold the ensuing nearly-identical rotation.

In both of those transitions there is going to be significant floating point precision loss, and I speculate that is what is preventing you from seeing the rotation “properly.”

I recommend instead that you store your own variable notion of “xrotation” (just an ordinary float) and then increment or decrement that variable and then assign it to the rotation.

I also prefer using this construct to assign rotations because it keeps you in mind of what is going on underneath.

 transform.rotation = Quaternion.Euler( xrotation, 0, 180);