How to stop running after a certain time?

I want to add a very simple time limit to the running portion of this script:

{
public float walkSpeed = 7; // regular speed
public float crchSpeed = 3; // crouching speed
public float runSpeed = 20; // run speed

private CharacterMotor chMotor;
private Transform tr;
private float dist; // distance to ground

// Use this for initialization
void Start () 
{
   chMotor =  GetComponent<CharacterMotor>();
    tr = transform;
    CharacterController ch = GetComponent<CharacterController>();
    dist = ch.height/2; // calculate distance to ground
}

// Update is called once per frame
void FixedUpdate ()
{
   float vScale = 1.0f;
    float speed = walkSpeed;

    if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && chMotor.grounded)
    {
        speed = runSpeed;       
    }

    if (Input.GetKey("c"))
    { // press C to crouch
        vScale = 0.5f;
        speed = crchSpeed; // slow down when crouching
    }

    chMotor.movement.maxForwardSpeed = speed; // set max speed
    float ultScale = tr.localScale.y; // crouch/stand up smoothly 

   Vector3 tmpScale = tr.localScale;
   Vector3 tmpPosition = tr.position;

   tmpScale.y = Mathf.Lerp(tr.localScale.y, vScale, 5 * Time.deltaTime);
   tr.localScale = tmpScale;

   tmpPosition.y += dist * (tr.localScale.y - ultScale); // fix vertical position       
   tr.position = tmpPosition;
}

}

Save the time you char started running, e.g:

if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && chMotor.grounded)
{
     speed = runSpeed;
     startedRunning = Time.time;
}

Gotta add that “float startedRunning” to your class ofcourse.
Then you can stop running with something like:

if ((Time.time - startedRunning) > 7) doSomething();

You could use a coroutine and yield for the amount of time you want the sprint to last.

if ((Input.GetKey("left shift") || Input.GetKey("right shift")) && chMotor.grounded)
{
    if(!sprinting)
    {
        speed = runSpeed;
        sprinting = true;
        StartCoroutine(sprintTimer);
     }      
}

Here’s the coroutine:

private IEnumerator sprintTimer()
{
      yield return new WaitForSeconds(sprintTime);
      speed = walkSpeed;
      sprinting = false;
}

You might need to add some code to stop the coroutine and reset the players speed if the shift key is released. Also to get rid of the if statement where you check for input from the shift key you could use getkeyDown instead of getKey so the code is only called when the key is pressed.

Thanks. I got it to work but I had to change some of the script.