Red
Red

Reputation: 33

Using helper functions inside trigger functions

I'm trying to use helper function in order to make the function pause for few seconds but it doesn't execute the wait function.

That's the code I've been using:

Code:

public class Triggers : MonoBehaviour {
    IEnumerator wait(float seconds) {
        Debug.Log("In wait");
        yield return new WaitForSeconds(seconds);
        Debug.Log("after wait");
    }

    void OnTriggerEnter(Collider _collider)
    {
        Debug.Log("Destroy");
        gameObject.SetActive(false);
        Debug.Log("Before wait");
        wait(5);
        Debug.Log("activate");
        gameObject.SetActive(true);
    }
}

I'd appreciate some help.

Upvotes: 0

Views: 522

Answers (2)

Red
Red

Reputation: 33

I solved it by just deactivating the child object which is the actual "physical" object I wanted to hide on collision with the invisible parent object.So now the parent object stays active, counting the time and the physical object "Cube" dis appears and reappears after n seconds.

   public class Triggers : MonoBehaviour
{
    IEnumerator wait (float seconds)
    {
        Debug.Log ("In wait");
        GameObject go = GameObject.Find ("Cube");
        go.SetActive(false);
        yield return new WaitForSeconds(seconds);
        Debug.Log ("after wait");
        go.SetActive (true);
    }

    void OnTriggerEnter (Collider _collider)
    {
        Debug.Log ("Destroy");
        Debug.Log ("Before wait");
        StartCoroutine (wait (5));
        Debug.Log ("activate");

    }

Upvotes: 2

Gauthier Boaglio
Gauthier Boaglio

Reputation: 10242

Try this :

StartCoroutine(wait(5));

instead of simply "wait(5)".

This is the way coroutines work in C#, if I remember well...

Upvotes: 0

Related Questions