Tracking the rotation of a cube

Hello, I’m at my wits end here. What I’m trying to do seems simple in theory, but Unity doesn’t seem to want to behave. What I’m doing is generating a random number between 1 and 5. Each of those numbers corresponds to the direction a cube should rotate (1 = 90 degrees up, 2 = 90 degrees down, etc (and 5 = 180 rotate on y axis)). This is all in a for loop. However, weird stuff starts happening, and I don’t know why. On the first command, the cube rarely rotates right (usually up to three times to intended value), and then there are problems where if the Y axis is 90, 270, etc, you need to rotate on the Z axis instead of the X. And then sometimes it works fine!

Here’s a watered down snippit of the code. I removed the stuff that deals with that Z axis thing, since it’s just a few if statements for the specific cases.

IEnumerator timeSpeed(){
		for(int i = 0; i < totalCommands; i++){


			nextDirection = Random.Range(1, 6);

			if(nextDirection == 1)
				trackX -= 90;
			if(nextDirection == 2)
				trackX += 90;
			if(nextDirection == 3)
				trackY -= 90;
			if(nextDirection == 4)
				trackY += 90;
			if(nextDirection == 5)
				trackY += 180;

			yield return new WaitForSeconds(time);

			if(i == totalCommands-1){
				gameOver = true;
				StopCoroutine("timeSpeed");
			}
		}
	}

Does anybody know another way to do this? Or a solution to my issue? It would be so helpful.

Thanks!

Just do not use Euler angles.

using UnityEngine;
using System.Collections;

public class RotationTest : MonoBehaviour
{
    public float rotationSpeed = 180;
    public float siclePauseTime = 0.5f;

	void Start ()
	{
	    StartCoroutine(RotationInitializer());
	}

    IEnumerator RotationInitializer()
    {
        while (true)
        {
            int axis = Random.Range(0, 3);

            switch (axis)
            {
                case 0:
                    yield return StartCoroutine(RotateTo(transform.rotation*Quaternion.AngleAxis(90 * Mathf.Sign(Random.Range(-1, 2)), Vector3.up)));
                    break;
                case 1:
                    yield return StartCoroutine(RotateTo(transform.rotation*Quaternion.AngleAxis(90 * Mathf.Sign(Random.Range(-1, 2)), Vector3.right)));
                    break;
                case 2:
                    yield return StartCoroutine(RotateTo(transform.rotation*Quaternion.AngleAxis(90 * Mathf.Sign(Random.Range(-1, 2)), Vector3.forward)));
                    break;
            }

            yield return new WaitForSeconds(siclePauseTime);
        }
    }

    IEnumerator RotateTo(Quaternion target)
    {
        while (Quaternion.Angle(transform.rotation, target)>0.5f)
        {
            transform.rotation = Quaternion.RotateTowards(transform.rotation, target, rotationSpeed*Time.deltaTime);
            yield return null;
        }
        transform.rotation = target;
    }
}