Search Unity

Chain of Events using Coroutine

Discussion in 'Scripting' started by avidesk, Sep 14, 2012.

  1. avidesk

    avidesk

    Joined:
    Sep 12, 2011
    Posts:
    62
    I'm new to coroutines, but I think what I'm wanting to do here is a good use for them, I just can't figure out how to do it. What I want to do is create a sort of wizard, where you step through a multi-step process each time the user clicks a button. I have created a rough sketch that I think conveys what I mean:



    How do I set up a coroutine to sit and loop on a step until the mouse is clicked, then move on to the next step. While in the 'wizard' portion of the code, "Do Something" should not execute.

    I know how I can do this using boolean flags or an integer to represent what 'step' I'm on, but I'd like to avoid that if possible.

    Thanks
     
    Last edited: Sep 14, 2012
  2. Loius

    Loius

    Joined:
    Aug 16, 2012
    Posts:
    546
    A pretty simple setup:

    Code (csharp):
    1. function ButtonLoop() {
    2.   var currentStage: int = 0;
    3.   var done : int = 4;
    4.   while ( currentStage < done ) {
    5.     currentStage = Display( currentStage );
    6.     yield;
    7.   }
    8. }
    9.  
    10. function Display( currentStage : int ) : int {
    11.   var returnValue : int = currentStage
    12.   switch( currentStage ) {
    13.      case 1:
    14.         // display/check button status, set returnValue to 2 if "next" was pressed, 0 if "back" was pressed
    15.         break;
    16.      /*...*/
    17.   }
    18.   return returnValue;
    19. }
    If you're dead-set against state variables, you can jam it all into the coroutine:

    Code (csharp):
    1. function ButtonLoop() {
    2.   while( !done ) {
    3.     // do stage one, set done when done
    4.     yield;
    5.   }
    6.   while( !done ) {
    7.     // do stage two, set done when done
    8.     yield;
    9.   }
    10.   while( !done ) {
    11.     // do stage three, set done when done
    12.     yield;
    13.   }
    14. }
    There will be complications with that, but they'll be fixable. (going back will be difficult, for example)

    Edit: If you're using OnGUI, you already essentially -have- your coroutine, since it has to run all the time anyway. It's easiest to use a state machine with OnGUI.
     
    Last edited: Sep 14, 2012