Hi.
I’ve read several topics about coroutines on the forum, and even though I understand the concept (or so I think), I’m having some troubles working with them.
What I’m trying to accomplish is to create a DownloadManager behaviour that could start and stop coroutines for downloading data over the Internet.
I successfully created and started the download of the WWW file, but I’m stuck with the Stop/Cancel function. Now, I know there is a StopCoroutine(“MyCoroutine”) that should match StartCoroutine(“MyCoroutine”, WWW myWWW) but unfortunately I can’t seem to get it to work. Here’s what I did so far :
using UnityEngine;
using System.Collections;
public class DownloadManager : MonoBehaviour {
public int maxDownloads = 1;
private GameObject[] downloads;
void Start() {
downloads = new GameObject[maxDownloads];
}
void Update() {
if (Input.GetKeyDown("b")) {
for (int i = 0; i < maxDownloads; i++) {
downloads[i] = new GameObject();
downloads[i].AddComponent<DownloadCoroutine>();
downloads[i].GetComponent<DownloadCoroutine>().Url = "http://www.website.com/bigimages/" + i + ".jpg";
downloads[i].GetComponent<DownloadCoroutine>().StartDownload();
}
}
if (Input.GetKeyDown("e")) {
for (int i = 0; i < maxDownloads; i++) {
downloads[i].GetComponent<DownloadCoroutine>().StopDownload();
}
}
}
}
Now, for stopping, I read several Dreamora’s posts about “state variables”.
So that’s what I’m trying to accomplish, but I’m not sure exactly how to do it correctly. I did that :
using UnityEngine;
using System.Collections;
public class DownloadCoroutine : MonoBehaviour {
private string url = "";
private bool inProgress = false;
private bool cancelled = false;
public string Url { get; set; }
public void StartDownload() {
inProgress = true;
WWW www = new WWW(url);
StartCoroutine("MyCoroutine", www);
}
public void StopDownload() {
if (inProgress) cancelled = true;
}
IEnumerator MyCoroutine(WWW www) {
yield return www;
inProgress = false;
if (!cancelled) {
if (www.error == null) {
Debug.Log("GOT IMAGE: " + url);
}
else {
Debug.Log("ERROR FOR IMAGE : " + url);
}
}
}
}
My question here is : how can setting my cancelled variable to “true” will stop the coroutine from running, cause from what I understood, the “if” statement will only be done once the download is already over ?
Thanks a lot.