How do I make something move for only a few seconds C#

So I’m getting more and more experienced in C# but I hit a small roadblock. I am making a claw game and I wanted to have this script which made the claw move down and then back up after you press space. So far, I have the script for it to move

using UnityEngine;
using System.Collections;

public class lift : MonoBehaviour {

	void Update () {
		if(Input.GetKey("space"))
		{
			transform.Translate(Vector3.down * Time.deltaTime);
		}
	}



		
	}

What I want to know is if there is a command for something to happen for only a period of time. In this case, I want the claw to move down for only about a second. Thanks in advance.

You hace to keep track of how much time the code has run, and only call it while the elapsed time is less than the duration you want. There’s nothing you can write in a single line that would do it.

It’s really simple anyway, the simplest code I can think of, without a coroutine, would be something like this:

using UnityEngine;

public class SomeScript : MonoBehaviour {

    public float duration; //set the duration in the inspector
    float elapsedTime = Mathf.Infinite;

    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            elapsedTime = 0f;
        }

        if (elapsedTime < duration) {
            transform.Translate(Vector3.down*Time.deltaTime);
            elapsedTime += Time.deltaTime;
        }
    }
}

A coroutine removes the need of class members and have other advantages, but adds some complexity. Something like this should work too:

using UnityEngine;

public class SomeScript : MonoBehaviour {

    public float duration; //set the duration in the inspector
   
    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            StartCoroutine(MoveDown());
        }
    }

    IEnumerator MoveDown() {
        float elapsedTime = 0f;
        while (elapsedTime < duration) {
            transform.Translate(Vector3.down*Time.deltaTime);
            elapsedTime += Time.deltaTime;
            yield return null;
        }
    }
}