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): using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.IO; public class StopMotionCameraController : MonoBehaviour { public RawImage cameraPanel; WebCamTexture webcamTexture; public Texture[] savedImages; int imageCount = 1; public RawImage playbackPanel; public bool loopPlaybackPanel; void Start () { webcamTexture = new WebCamTexture(null, 1024, 768); cameraPanel.texture = webcamTexture; webcamTexture.Play(); } public void TakeAFrame() { StopCoroutine(PlaybackCoroutine()); Texture2D texture = new Texture2D(cameraPanel.texture.width, cameraPanel.texture.height, TextureFormat.ARGB32, false); texture.SetPixels(webcamTexture.GetPixels()); texture.Apply(); System.Array.Resize(ref savedImages, imageCount+1); savedImages[imageCount] = texture; imageCount ++; StartCoroutine(PlaybackCoroutine()); } IEnumerator PlaybackCoroutine() { while (loopPlaybackPanel) { for (int i = 0; i < savedImages.Length; i++) { yield return new WaitForSeconds (1f); playbackPanel.texture = savedImages[i]; } } } }
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);