Start a Coroutine in a Method, wait there until it's finished

Hi there,

this is my method I want to start a coroutine from:

private Material loadMaterialFromWeb(string path, string savePath)
    {
        StartCoroutine(getMatFromWeb(path,savePath));

        //wait here until coroutine finished

        return newMat;
    }

The coroutine downloads a picture from web, creates a material out of it and writes it to the global variable newMat. This global variable (or any other material variable) should be returned as this method relies on an interface I do not want to change.

So how can I tell this method to wait until newMat has been filled? The coroutine contains a flag which indicates whether the material has been successfully created, but I couldn’t find a way to check this properly.

Use a while loop.

while (newMath == null) {
//do nothing
}

Or add a boolean flag in the coroutine and put the boolean in the while loop

while (!isFinished)

Why do you even need a coroutine for this?

Wouldn’t it just be easier to do:

newMath = getMatFromWeb(path,savePath)
return newMath;

I gonna guess your code kinda looks like this:

private Material newMat;

private Material loadMaterialFromWeb(string path, string savePath)
 {
     StartCoroutine(getMatFromWeb(path,savePath));

     //wait here until coroutine finished

     return newMat;
 }

private IEnumerator getMatFromWeb(string path, string savePath)
 {
     //Wait for web request
     //if web request true set newMat to data from web request
     //Else send error message
 }

If you want to make this class as some kind of generator i suggest do something like:

MonoBehaviour class say MaterialGenerator.cs:

 public Material newMat;

 public IEnumerator loadMaterialFromWeb(string path, string savePath)
  {
	  yield return getMatFromWeb(path,savePath);
  }

 private IEnumerator getMatFromWeb(string path, string savePath)
  {
	  //Wait for web request
	  //if web request true set newMat to data from web request
	  //Else send error message
	  yield return null;
  }

The MonoBehaviour who gonna use it.

public Material someMaterial;
public MaterialGenerator temp; //gameobject component

public IENumerator DoStuff(){
	yield return temp.loadMaterialFromWeb(path, savepath);
	someMaterial = temp.newMat;
	yield return null;
}