Search Unity

WaitForSeconds in Coroutine

Discussion in 'Scripting' started by nm8shun, Aug 12, 2017.

  1. nm8shun

    nm8shun

    Joined:
    Jul 14, 2007
    Posts:
    476
    I've got a script in which I hit a UI button that fires the TakeAFrame function. In theory, this is supposed to extend an array that contains images. These images are to play back in a loop.

    But, in the script below, the WaitForSeconds doesn't seem to work. The more times the TakeAFrame function is activated, the faster the images playback. Clearly I don't understand something about Coroutines or how WaitForSeconds reacts in them.

    Any hints?

    Code (csharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6. using System.IO;
    7.  
    8. public class StopMotionCameraController : MonoBehaviour {
    9.     public RawImage cameraPanel;
    10.     WebCamTexture webcamTexture;
    11.     public Texture[] savedImages;
    12.     int imageCount = 1;
    13.  
    14.     public RawImage playbackPanel;
    15.     public bool loopPlaybackPanel;
    16.  
    17.  
    18.     void Start ()
    19.     {
    20.         webcamTexture = new WebCamTexture(null, 1024, 768);
    21.         cameraPanel.texture = webcamTexture;
    22.         webcamTexture.Play();
    23.     }
    24.  
    25.     public void TakeAFrame()
    26.     {
    27.         StopCoroutine(PlaybackCoroutine());
    28.  
    29.         Texture2D texture = new Texture2D(cameraPanel.texture.width, cameraPanel.texture.height, TextureFormat.ARGB32, false);
    30.  
    31.         texture.SetPixels(webcamTexture.GetPixels());
    32.         texture.Apply();
    33.  
    34.         System.Array.Resize(ref savedImages, imageCount+1);
    35.         savedImages[imageCount] = texture;
    36.         imageCount ++;
    37.  
    38.         StartCoroutine(PlaybackCoroutine());
    39.     }
    40.  
    41.     IEnumerator PlaybackCoroutine()
    42.     {
    43.         while (loopPlaybackPanel)
    44.         {
    45.             for (int i = 0; i < savedImages.Length; i++)
    46.             {
    47.                 yield return new WaitForSeconds (1f);
    48.                 playbackPanel.texture = savedImages[i];
    49.             }
    50.         }
    51.     }
    52. }
    53.  
     
  2. Nickromancer

    Nickromancer

    Joined:
    Jul 31, 2016
    Posts:
    92
    The StopCoroutine() doesn't work like this.

    You should store an instance of Coroutine returned by StartCoroutine() and give that to StopCoroutine().

    example:

    var theRoutine = StartCoroutine(PlaybackCoroutine());
    // ...
    StopCoroutine( theRoutine);
     
  3. nm8shun

    nm8shun

    Joined:
    Jul 14, 2007
    Posts:
    476
    Thanks much Nickromancer....