Search Unity

How can i use a bool variable to decide if to use a StartCoroutine ?

Discussion in 'Scripting' started by Chocolade, Aug 18, 2017.

  1. Chocolade

    Chocolade

    Joined:
    Jun 19, 2013
    Posts:
    933
    In one script at the top:

    Code (csharp):
    1.  
    2. public bool generationDelay = false;
    3.  
    Then in a method, there was only StartCoroutine i added all the IF statement using the bool variable:

    Code (csharp):
    1.  
    2.     private void BeginGame()
    3.         {
    4.             mazeInstance = Instantiate(mazePrefab) as Maze;
    5.    
    6.             if (generationDelay == true)
    7.             {
    8.                 StartCoroutine(mazeInstance.Generate(generationDelay));
    9.             }
    10.             else
    11.             {
    12.                 mazeInstance.Generate(generationDelay);
    13.             }
    14.         }
    15.  
    Then in another script in the Generate method:

    Code (csharp):
    1.  
    2.     public IEnumerator Generate (bool generationDelay) {
    3.    
    4.             if (generationDelay == true)
    5.             WaitForSeconds delay = new WaitForSeconds(generationStepDelay);
    6.             cells = new MazeCell[size.x, size.z];
    7.             List<MazeCell> activeCells = new List<MazeCell>();
    8.             DoFirstGenerationStep(activeCells);
    9.             while (activeCells.Count > 0) {
    10.                 yield return delay;
    11.                 DoNextGenerationStep(activeCells);
    12.             }
    13.         }
    14.  
    When i added this line inside Generate:

    Code (csharp):
    1.  
    2. if (generationDelay == true)
    3.  
    I'm getting error on the line:

    WaitForSeconds delay = new WaitForSeconds(generationStepDelay);

    The error message:

    Embedded statement cannot be a declaration or labeled statement

    And also error on the line:
    On the delay:

    Code (csharp):
    1.  
    2. yield return delay;
    3.  
    The name 'delay' does not exist in the current context

    What i want is a public bool variable to decide if to use or not StartCoroutine.
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,532
    'delay' only gets declared if delay is true but the while statement is executed regardless, so 'delay' is potentially never declared. There's no reason you should even be checking the delay bool again inside the coroutine because you're doing that before you start the coroutine.

    Looks like you've largely overcomplicated the issue.