rotate object at limited angle

i want to rotate an abject at limited angle by holding key and when unpress a key the angle return to it’s initial angle How i can do this??

Hey @unity_krXvMvBdCJvbSQ, a lot depends on details about your implementation preferences. I’ll make a few assumptions:

  1. The rotation to and from the target (limited) angle is instantaneous, and not animated over time.

  2. The rotation in the example that follows is in the Y axis of a 3d object

  3. The rotation applies to the object’s local coordinate system

  4. The key in this example is “R”

Something like this might do:

public class ScriptonGameObject : MonoBehaviour 
{
  private bool  isRotated = false;                                
    Quaternion  prevOrientation;
 private float  targetAngle = 30f; 

 void Update()
    {
     if ( Input.GetKey( KeyCode.R ) ) 
          {
           if ( isRotated == false )
              {
               isRotated = true;
               prevOrientation = new Quaternion( transform.localRotation.x, 
                                                 transform.localRotation.y, 
                                                 transform.localRotation.z, 
                                                 transform.localRotation.w );

               transform.localRotation = Quaternion.Euler( prevOrientation.x, 
                                                           prevOrientation.y + targetAngle,
                                                           prevOrientation.z );
              }
          }
     else {
           if ( isRotated == true )
              {
               isRotated = false;
               transform.localRotation = prevOrientation;
              }
          }     
    }
}

The objective is to sense if the key is down or not.

When down, if the rotation has not already been applied, apply the rotation after storing the current orientation in prevOrientation.

When up, determine if the object had been rotated, and if so, restore the original orientation and note the object is no longer rotated.