What is the best way to do a delay in void Update? There’s the I WANT THE DELAY HERE where i want to place it.
void Update ()
{
if (lidCheck == false)
{
myLight.range = Mathf.Lerp(myLight.range, 0.0f, Time.deltaTime * 3);
**I WANT THE DELAY HERE**
Sparks.SetActive(false);
Fire.SetActive(false);
Flames.SetActive(false);
Glow.SetActive(false);
}
if (lidCheck == true)
{
myLight.range = Mathf.Lerp(myLight.range, 6.0f, Time.deltaTime/2);
Sparks.SetActive(true);
Fire.SetActive(true);
Flames.SetActive(true);
Glow.SetActive(true);
}
}
void OnTriggerStay (Collider other)
{
if (other.gameObject.tag == "Player")
{
if (Input.GetKey(KeyCode.E))
{
anim.Play("openlid");
lidCheck = true;
}
if (Input.GetKey(KeyCode.R))
{
anim.Play("closelid");
lidCheck = false;
}
}
}
I don’t advise you to use the Update
function in your case but coroutines:
void OnTriggerStay (Collider other)
{
if (other.gameObject.tag == "Player")
{
if (Input.GetKey(KeyCode.E))
{
StartCoroutine( OpenLid() ) ;
}
if (Input.GetKey(KeyCode.R))
{
StartCoroutine( CloseLid() ) ;
}
}
}
IEnumerator OpenLid()
{
anim.Play("openlid");
float initialRange = myLight.range ;
float lerpDuration = 1 ;
for( float t = 0 ; t < lerpDuration ; t += Time.deltaTime )
{
myLight.range = Mathf.Lerp(initialRange, 0.0f, t / lerpDuration);
yield return null ;
}
Sparks.SetActive(false);
Fire.SetActive(false);
Flames.SetActive(false);
Glow.SetActive(false);
}
IEnumerator CloseLid()
{
anim.Play("closelid");
float initialRange = myLight.range ;
float lerpDuration = 2 ;
Sparks.SetActive(true);
Fire.SetActive(true);
Flames.SetActive(true);
Glow.SetActive(true);
for( float t = 0 ; t < lerpDuration ; t += Time.deltaTime )
{
myLight.range = Mathf.Lerp(initialRange, 6.0f, t / lerpDuration);
yield return null ;
}
}
If you really want to keep your Update function, try this:
private float lidClosedTime ;
void Update ()
{
if (lidCheck == false)
{
myLight.range = Mathf.Lerp(myLight.range, 0.0f, Time.deltaTime * 3);
if( Time.time - lidClosedTime > 2 )
{
Sparks.SetActive(false);
Fire.SetActive(false);
Flames.SetActive(false);
Glow.SetActive(false);
}
}
if (lidCheck == true)
{
myLight.range = Mathf.Lerp(myLight.range, 6.0f, Time.deltaTime/2);
Sparks.SetActive(true);
Fire.SetActive(true);
Flames.SetActive(true);
Glow.SetActive(true);
}
}
void OnTriggerStay (Collider other)
{
if (other.gameObject.tag == "Player")
{
if (Input.GetKey(KeyCode.E))
{
anim.Play("openlid");
lidCheck = true;
}
if (Input.GetKey(KeyCode.R))
{
anim.Play("closelid");
lidCheck = false;
lidClosedTime = Time.time ;
}
}
}
Thank you so much!! It’s perfect, i could kiss you.