Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

OnBecameInvisible can be a Co-routine?

Discussion in 'Scripting' started by CesarNascimento, Feb 18, 2016.

  1. CesarNascimento

    CesarNascimento

    Joined:
    Mar 26, 2013
    Posts:
    15
  2. Teravisor

    Teravisor

    Joined:
    Dec 29, 2014
    Posts:
    654
    Code (CSharp):
    1. IEnumerator isStarted;
    2. IEnumerator OnBecameInvisible()
    3. {
    4.     isStarted = new WaitForSeconds(4f);
    5.     yield return isStarted;
    6.     gameObject.SetActive(false);
    7. }
    8. void OnBecameVisible()
    9. {
    10.     if(isStarted!=null)
    11.     {
    12.         StopCoroutine(isStarted);
    13.         isStarted=null;
    14.     }
    15. }
    16.  
    Will disable object if it was invisible for 4 seconds or more, but won't disable it if it is visible at least once per 4 seconds. Good for things you want to despawn when they're off screen for long.

    In general, you could use it for any delayed action (do something after X time passed or on next frame).

    P.S. Start() can be coroutine too.
     
    Last edited: Feb 18, 2016
  3. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    most of the unity messages a MonoBehaviour can receive can all be made coroutines, and unity will automatically run them as such. With some exceptions (like Awake).

    This is just as a short cut, so that you don't have to start the coroutine yourself (which would make you have 2 methods, instead of 1).

    Code (csharp):
    1.  
    2. function OnBecameInvisible()
    3. {
    4.     StartCoroutine(SomeRoutine());
    5. }
    6.  
    7. function SomeRoutine()
    8. {
    9.     //do stuff
    10.  
    11.     yield WaitForSeconds(1f);
    12.  
    13.     //do stuff
    14. }
    15.  
    16. //vs
    17.  
    18. function OnBecameInvisible()
    19. {
    20.     //do stuff
    21.  
    22.     yield WaitForSeconds(1f);
    23.  
    24.     //do stuff
    25. }
    26.  
    In this example, what if 'OnBecameInvisible' you wanted to wait a second. You can.

    Who knows what you'll want to do. The possibilities are infinite.
     
    CesarNascimento likes this.
  4. CesarNascimento

    CesarNascimento

    Joined:
    Mar 26, 2013
    Posts:
    15
    Thanks Teravisor and lordofduct!
    That really opened up a lot of possibilities for me.