# rotate objects with keys

Hello friends!

I have a game project, now when I run the game, there is one object if I press space then the object will rotate y, but if I don’t press space, the rotation of the object will return to its original state.

I really need the script.

I like the answer of @DCordoba - here just another solution I came up with. Good night

``````using System;
using UnityEngine;

public class RotateAndBack : MonoBehaviour {
[SerializeField] RotationAxis _rotationAxis;
[SerializeField, Range(1, 360)] float _degreePerSecond = 10f;

Transform _transform;
Quaternion _defaultRotation;
float _degreesRotated;

void Start() {
_transform = transform;
_defaultRotation = _transform.rotation;
}

void Update() {
if (Input.GetKey(KeyCode.Space)) DoRotate(_degreePerSecond);
else if (_degreesRotated > 0) DoRotate(-_degreePerSecond);
else if (_degreesRotated != 0) {
_degreesRotated = 0;
_transform.rotation = _defaultRotation;
}
}

void DoRotate(float degrees) {
var rotAxis = ByRotationAxisEnumValue(_rotationAxis);
var timedDegree = degrees * Time.deltaTime;

_transform.Rotate(rotAxis, timedDegree);

_degreesRotated += timedDegree;
_degreesRotated %= 360f;
}

enum RotationAxis {
AROUND_POS_X_AXIS,
AROUND_POS_Y_AXIS,
AROUND_POS_Z_AXIS,
AROUND_NEG_X_AXIS,
AROUND_NEG_Y_AXIS,
AROUND_NEG_Z_AXIS
}

Vector3 ByRotationAxisEnumValue(RotationAxis rotationAxis) {
switch (rotationAxis) {
case RotationAxis.AROUND_POS_X_AXIS: return Vector3.right;
case RotationAxis.AROUND_POS_Y_AXIS: return Vector3.up;
case RotationAxis.AROUND_POS_Z_AXIS: return Vector3.forward;
case RotationAxis.AROUND_NEG_X_AXIS: return Vector3.left;
case RotationAxis.AROUND_NEG_Y_AXIS: return Vector3.down;
case RotationAxis.AROUND_NEG_Z_AXIS: return Vector3.back;
default: throw new Exception("UNKNOWN RotationAxis");
}
}
}
``````