How to rotate object back and forth on input hold?

I tried mathf.PingPong but it seems to be always active/rotating behind the scene even when i don’t press anything.

I need it to rotate back and forth when i hold the button, return to it’s starting rotation on release, and start rotate again from the starting rotation when i hold the button.

This is the code that i have now.

using UnityEngine;
using System.Collections;

public class HoldToRotate : MonoBehaviour
{
    private Quaternion startingRotation;
    public float rot = 180;
    public float rotSpeed = 10;

    void Start()
    {
        startingRotation = transform.rotation;
    }

    void Update()
    {
        if (Input.GetKey(KeyCode.F))
            PingPongRotation();
            
        else if (Input.GetKeyUp(KeyCode.F))
            transform.rotation = startingRotation;
    }

    void PingPongRotation()
    {
        transform.localEulerAngles = new Vector3(-Mathf.PingPong(Time.time * rotSpeed, rot), 0,0);
    }
}

Hi @Babars,

That problem is due to Time.time in Mathf.PingPong().

So find solution below :

float _tempTime = 0;
	void PingPongRotation ()
	{
		_tempTime += Time.deltaTime;
		transform.localEulerAngles = new Vector3 (-Mathf.PingPong (_tempTime * rotSpeed, rot), 0, 0);
	}