Rotation in Script - not working

Hi guys,
Sorry if the title seems a bit vague, but I have a script, which says:

	if (direction == 1) {
		transform.rotation.y = 180;
	}
	if (direction == 2) {
		transform.rotation.y = 0;
	}
	if (direction == 3) {
		transform.rotation.y = 270;
	}
	if (direction == 4) {
		transform.rotation.y = 90;
	}
	transform.rotation.x = 270;
	transform.rotation.z = 0;

so whatever its applied to should get the rotation:

x = 270
y = whatever
z = 0

but instead it gets (as rotation):

x = 0.42
y = 180
z = 180

in the inspector during game play.

Does anyone know why this is/or how to fix this?

Transform.rotation is a Quaternion…a 4D construct. From the reference:

[Quaternions] are based on complex numbers and are not easy to understand intuitively. Thus you almost never access or modify individual Quaternion components (x,y,z,w).

You can indirectly modify the rotation using Transform.eulerAngles. But there are some gotchas with this as well. First from the reference:

Do not set one of the eulerAngles axis separately (eg. eulerAngles.x = 10; ) since this will lead to drift and undesired rotations. When setting them to a new value set them all at once.

In addition, eulerAngles suffer from the same problem you have above. That is there are multiple euler angles representations for any given ‘physical’ rotation. So if you set the euler angles to (180,0,0), the values you read back might be (0,180,180)…the same physical rotation represented differently.

One solution is to view eulerAngles as ‘write-only’. That is, you keep your own Vector3 which you manipulate. Then you assign the rotation. So for your code above, if you had a Vector3 called ‘myRotation’; You might:

if (direction == 1) {
       myRotation.y = 180;
    }
    if (direction == 2) {
       myRotation.y = 0;
    }
    if (direction == 3) {
       myRotation.y = 270;
    }
    if (direction == 4) {
      myRotation.y = 90;
    }
    myRotation.x = 270;
    myRotation.z = 0;
    transform.eulerAngles = myRotation;

Since you are the only one manipulating myRotation, the values will always be the ones you expect.