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.
Corutines are used for making things happen over a period of time so maybe something useful there i have not used it in this way before though. but you can use corutines to make a texture flash red or something to show damage so should be useful for this.
Or actually using a lerp method would be better as you can set the target position you want to reach and how long you want to tak to get there the is vector.lerp and mathf.lerp this would be good as you will not overshoot your target position if that is important
Answer by DiegoSLTS · Sep 18, 2015 at 06:44 PM
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;
}
}
}
Your answer
Follow this Question
Related Questions
I make a timing score script in unity 2D, how i make high score of time?? Script is as follow: 1 Answer
Time.time doesn't show up? 2 Answers
Trying to Generate Different Random Values for Position of Game Object Instances [C#] 1 Answer
Trying to move buttons via Coroutine and transform.Translate 0 Answers
why the camera rotate in the z axis 0 Answers