[SOLVED] C# Triggering a delay with Coroutine (IEnumerator)

Hi all,

I am trying to insert a 5 second delay, separating two Get.Components at the end of the below code.
Tried using the iEnumerator function, but not getting it to work.

Any ideas?

using UnityEngine;
using System.Collections;

public class OnTriggerStayTimerFrogDeactivate : MonoBehaviour
{
    public GameObject projectilePrefab;
    float t = 0;
    private bool canInstantiateProjectile = true;
   
   
   
       

  void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Fly")
            t = 0;
    }




    void OnTriggerStay(Collider other)
    {

        if (other.gameObject.tag == "Fly")
            t += Time.deltaTime;
        if (t > 0)
        {
            if (canInstantiateProjectile)
             
             
             
            {
               
         
                 
            GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = false;
           
           
                        }
       
               
       
       
 GetComponent<Animator>().CrossFade("Frog_Static", 0f);



// I'D LIKE TO INSERT A 5 SEC DELAY HERE



                  GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = true;
                   
                   GetComponent<Animator>().CrossFade("Frog_Hungry", 0f);      
                   
                   
                   
                 

                       }
    }

}

Youā€™ll have to create a new method and use Unityā€™s ā€œInvokeā€ method to invoke it.

See here: Unity - Scripting API: MonoBehaviour.Invoke

Is this because iEnumerator canā€™t be used?
Do I need to create a separate script and then invoke within the above?

No, you do not need to create a separate script. You can use a coroutine as well but using Invoke is simpler and easier.
Check the page I linked for an example on how to call a method with a delay using ā€œInvokeā€.

Sorry, Iā€™m a little confused- that example was javascript and Iā€™m working in C#.
Would you have any suggestions how to accomplish this in C#?
Thanks.

This is the IEnumerator script that Iā€™m trying to use with the above:

IEnumerator Process()
{


//Wait 1 second
yield return StartCoroutine(Wait(1.0f));
//Do process stuff
}


IEnumerator Wait(float seconds)
{
yield return new WaitForSeconds(seconds);
}

Still stumped here. Any ideas?

How is using invoke more efficient than a coroutine?

there is a language toggle top right on pretty much all the scripting reference pages.

Youā€™re going to run into issues any which way you do the delay since you are calling it from ā€œOnTriggerStayā€ which is called every frame, so you will start a new coroutine, or invoke a new function every frame, which will all then run their course and not end up doing what you want.

Perhaps you could explain what you are trying to achieve (and I donā€™t expect an answer of ā€œIā€™m trying to put in a delayā€ā€¦ :P)

Hi, thanks for your reply.
What Iā€™m trying to do is insert a delay between the following:

     GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = false;
          
         
                       }
      
              
      
      
GetComponent<Animator>().CrossFade("Frog_Static", 0f);






// I'D LIKE TO INSERT A 5 SEC DELAY HERE.






                  GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = true;
                  
                   GetComponent<Animator>().CrossFade("Frog_Hungry", 0f);

Also, just saw the toggle on page- thanks!

Hi all,

Still not having much luck getting the invoke method to work with the above code.
How would I alter the below script to create a delay with the above?

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
public Rigidbody projectile;
void LaunchProjectile() {
Rigidbody instance = Instantiate(projectile);
instance.velocity = Random.insideUnitSphere * 5;
}
void Example() {
Invoke("LaunchProjectile", 2);
}
}
1 Like

For both the Invoke and the coroutine approaches: place the code after your comment in a new method.

If you want to use Invoke: simply call the method using Invoke(ā€œYourNewMethodā€, 2);

If you want to use coroutines:

void OnTriggerStay(Collider other)
{
    // Beginning of your method here
    // ...

    GetComponent<Animator>().CrossFade("Frog_Static", 0f);
    // I'D LIKE TO INSERT A 5 SEC DELAY HERE
    StartCoroutine(WaitAndAnimate(5.0F));
}


IEnumerator WaitAndAnimate(float waitTime) {
    yield return new WaitForSeconds(waitTime);
    GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = true;
    GetComponent<Animator>().CrossFade("Frog_Hungry", 0f);
}

And as LeftyRighty said, make sure you add a check so you donā€™t start this delay timer every frame.

Thanks for your help, nygren!
I donā€™t think I need to use OnTriggerStay after all.
Iā€™ve put the following together, but still throwing errors:

using UnityEngine;
using System.Collections;

public class OnTriggerStayTimerFrogDeactivate : MonoBehaviour
{
  
public GameObject projectilePrefab;
    float t = 0;
    private bool canInstantiateProjectile = true;

  
      

  void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Fly")
            t = 0;
    }


{
  GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = false;
  GetComponent<Animator>().CrossFade("Frog_Static", 0f);
    // I'D LIKE TO INSERT A 5 SEC DELAY HERE
  
    StartCoroutine(WaitAndAnimate(5.0F));
}


IEnumerator WaitAndAnimate(float waitTime) {
    yield return new WaitForSeconds(waitTime);
       GetComponent<Animator>().CrossFade("Frog_Hungry", 0f);
       GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = true;



}

This seems like it should work. Is it a syntax error?

I donā€™t know, is it? Youā€™re the one who can see your console, not us. You saying itā€™s ā€œthrowing errorsā€, but donā€™t tell us what those errors are.

Iā€™m getting the following error for the above:

(26,1): error CS1519: Unexpected symbol `{ā€™ in class, struct, or interface member declaration

It looks like that } and the { after it shouldnā€™t be there. Thatā€™s all supposed to run in OnTriggerEnter, right?

It looks like you may also be missing a } at the very end of the script.

May help to make MonoDevelop re-do all your indents; it should make curly bracket errors more obvious. Select everything, and hit alt-down or alt-up.

Thanks, StarManta.
I re-wrote a couple of lines and added in the OnTriggerStay- not sure if really needed.
Regardless, Iā€™m still getting a parsing error and:

OnTriggerStayTimerFrogDeactivate2.cs(48,27): error CS1525: Unexpected symbol (', expecting )ā€˜, ,', ;ā€™, [', or =ā€™

My current code:

using UnityEngine;
using System.Collections;
public class OnTriggerStayTimerFrogDeactivate2 : MonoBehaviour
{
   
public GameObject projectilePrefab;
float t = 0;
private bool canInstantiateProjectile = true;
       

void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Fly")
t = 0;
}




void OnTriggerStay(Collider other)
{

if (other.gameObject.tag == "Fly")
t += Time.deltaTime;
if (t > 0)
{
if (canInstantiateProjectile)

{
               

               
GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = false;
GetComponent<Animator>().CrossFade("Frog_Static", 0f);
           
           
}
         
// THIS IS WHERE I WANT TO HAVE 5 SEC DELAY
         
StartCoroutine(WaitAndAnimate(5.0F));
IEnumerator WaitAndAnimate(float waitTime) {
yield return new WaitForSeconds(waitTime);
         
   

GetComponent<Animator>().CrossFade("Frog_Hungry", 0f);
GetComponent<AI_FindObjectsWithtag_Transform_Fly>().enabled = true;



}}}}