I want my script to wait 2 seconds before continue in a condition, in update, using C#
Here is what i got:
using UnityEngine; using System.Collections;
public class Compuerta : MonoBehaviour {
public int lobajo = -10;
public GameObject player;
public GameObject compuertilla;
private Animator comp;
void Start () {
comp = gameObject.GetComponentInChildren<Animator>();
}
void Update () {
if (player.transform.position.y < lobajo) {
comp.SetInteger ("Autocom", 1);
compuertilla.GetComponent<MeshCollider> ().enabled = false;
}
else if (player.transform.position.y > lobajo) {
**//Here is where I want it to wait for 2 seconds**
comp.SetInteger ("Autocom", 0);
compuertilla.GetComponent<MeshCollider> ().enabled = true;
}
}
}
I have searched, but nobody answer it for an update, can someone help me pls?
Answer by Arkaid · Jul 27, 2016 at 12:44 AM
Use Coroutines!
public class Compuerta : MonoBehaviour
{
public int lobajo = -10;
public GameObject player;
public GameObject compuertilla;
private Animator comp;
void Start ()
{
comp = gameObject.GetComponentInChildren<Animator>();
StartCoroutine(UpdateCoroutine());
}
IEnumerator UpdateCoroutine()
{
while(true)
{
if (player.transform.position.y < lobajo)
{
comp.SetInteger ("Autocom", 1);
compuertilla.GetComponent<MeshCollider> ().enabled = false;
}
else if (player.transform.position.y > lobajo)
{
**//Here is where I want it to wait for 2 seconds**
yield return new WaitForSeconds(2);
comp.SetInteger ("Autocom", 0);
compuertilla.GetComponent<MeshCollider> ().enabled = true;
}
yield return null;
}
}
}
Answer by Nitin22 · Jul 27, 2016 at 06:24 PM
Ok You can by using time vairable in Update :
public int lobajo = -10;
public GameObject player;
public GameObject compuertilla;
private Animator comp;
float timeCount;
public float delayTime = 2.0f;
void OnEnable ()
{
timeCount = 0;
}
void Start ()
{
comp = gameObject.GetComponentInChildren<Animator> ();
}
void Update ()
{
if (timeCount < delayTime) {
timeCount += Time.deltaTime;
return;
}
if (player.transform.position.y < lobajo) {
comp.SetInteger ("Autocom", 1);
compuertilla.GetComponent<MeshCollider> ().enabled = false;
} else if (player.transform.position.y > lobajo) {
**//Here is where I want it to wait for 2 seconds**
comp.SetInteger ("Autocom", 0);
compuertilla.GetComponent<MeshCollider> ().enabled = true;
}
}
Just by looking it, makes me think that it isn't what I wanted (because the delay isn't happening in the space that I wanted); but it's okay, Arkaid already helped me. In any way, thanks :)
Your answer
Follow this Question
Related Questions
I create material with script but it does not render right 0 Answers
Creating Splines from empties in script 0 Answers
how to ask if something is not true for an amount of time 2 Answers
How can i check if the alpha color or the material color is transparent ? 1 Answer
How do I make somthing happen when the Player reaches a certain x, y, z position? 0 Answers