How do I rotate a game object in 45 degree steps per keystroke?

I’d Like to start by first admitting that I am extremely new to any kind of scripting and this is quite literally the first time I have ever used c#. In my scene/script I have an empty game object which is the parent of my camera and thus is the focal point for my camera. Through my script I am able to move this around having my camera follow from a fixed position. After hours of struggling and much referring to the documentation, I was able to make the camera rotate in 45 degree increments around the y-axis of the focal point in both directions at the the touch of a key. However, the issue I’m running into now is that the object continually rotates (quite fast). Ideally I would like the object to only rotate 45 degrees per keystroke. Here is an example of what I have so far:

using UnityEngine;
using System.Collections;

public class cameraController : MonoBehaviour {

	public float speed;
	public GameObject camera;
	private Vector3 currentPos;
	private Vector3 currentRotation;

	void Update () {

		//Keep the camera focused on the target
		currentPos = transform.position;
		camera.transform.LookAt (currentPos);
		//currentRotation = transform.rotation.eulerAngles;
	}


	void LateUpdate () {

		//Horizontal Movement
		float moveHorizontal = Input.GetAxis ("Horizontal");
		float moveVertical = Input.GetAxis ("Vertical");
		Vector3 movement = new Vector3 (moveHorizontal, 0, moveVertical);

		transform.position = currentPos + movement * Time.deltaTime * speed;



	}

	void FixedUpdate () {

		//Camera rotation around the focal point
		float rotateFloat = Input.GetAxis("RotateY");
		int rotateY = Mathf.RoundToInt(rotateFloat);
		Quaternion currentRotation = transform.rotation;
		
		
		if (rotateY > 0) {
			
			transform.rotation = currentRotation * Quaternion.Euler(0, 45.0f, 0);
			Debug.Log("1");
		}
		if (rotateY < 0) {
			
			transform.rotation = currentRotation * Quaternion.Euler(0, -45.0f, 0);
			Debug.Log("2");
		}

		}
}

Use an Input.GetButton or Input.GetButtonDown method for this. The Input.GetAxis is for continuous movement, but the situation you have described is for the movement to take place in discrete steps at the press of a button or key. For instance, per the docs, Input.GetButtonDown will only return true during the frame that the button was pressed.

Just call Input.GetAxisRaw(“AxisName”), but add some extra code…

C#:

private bool usingAxis = false;
 
void Update(){
    if( Input.GetAxisRaw("AxisName") != 0){
        if(usingAxis == false){
            // Do your axis action here
            usingAxis = true;
        }
    }
    if( Input.GetAxisRaw("AxisName") == 0){
        usingAxis = false;
    }    
}

This should work (I’ll explain why in the comment section). If it does, please mark this answer as correct so others can see it and learn as well, ask their own questions, and grow the Unity community.

Happy Coding!

Noah.