Script not obeying?

I got a simple script that says:

function Update(){
  if(Input.GetButton("Left"){
  transform.rotation.y = 180.0;
  }
   
  if(Input.GetButton("Right"){
  transform.rotation.y = 0.0;
  }
}

But when I go into the game and tried it out, the gameobject just flip between 0 and 270. Any idea why?

P.S. I’m not intending to make the object rotate, just flip about.

I think this is what you are after:

function Update(){ 

	if(Input.GetKeyDown(KeyCode.LeftArrow))
		transform.rotation.y = 180.0;

	if(Input.GetKeyDown(KeyCode.RightArrow))
		transform.rotation.y = 0.0;
	
}

'rotation is a Quaternion, and unless you know what you are doing, it is not advised to to directly manipulate Quaternions. You can modify transform.eulerAngles, but the script reference says:

Do not set one of the eulerAngles axis separately (eg. eulerAngles.x = 10; )

So to get the behavior you want, you can start with your own Vector3 set to (0,0,0), modify it and assign it:

if(Input.GetButton("Left"){
  myVector.y = 180.0;
  transform.eulerAngles = myVector3;
  }

or you can use a relative rotation such as transform.Rotate(Vector3(0,-90,0));