N0xus
N0xus

Reputation: 2724

IEnumerator yielding to the result of another IEnumerator

I have two classes set up in my project.

On a button press in the first class I am calling the first IEnumerator on a button press:

if(GUI.Button(new Rect(250, 0, 100, 20), "clear"))
{
   StartCoroutine(Foo.test());
}

The method being called looks like this (in the other class):

public static IEnumerator test()
{     
    yield return StartCoroutine(DownloadAndCache());
    // do stuff
}

However, I'm intending this method to only carry out its actions once it gets a return from a second IEnumerator that pings a server and waits a few seconds to get a result.

This method looks like so:

IEnumerator  DownloadAndCache ()
{
    // Wait for the Caching system to be ready
    while (!Caching.ready)
        yield return null;

    Debug.Log("downloading asset bundle");
    // Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
    using(WWW www = WWW.LoadFromCacheOrDownload (jsonURL, version))
    {
        yield return www;
        if (www.error != null)
        {
            throw new Exception("WWW download had an error: " + www.error);
        }

        AssetBundle bundle = www.assetBundle;
        if (AssetName == "")
        {
            Instantiate(bundle.mainAsset);
        }
        else
        {
            Instantiate(bundle.Load(AssetName));
        }

        bundle.Unload(false);

    } 
}

However, when I implement this, my test method claims to not be set to an instance. I don't want to make a new copy of these scripts as I would need to reset the link each time. Is there a way I can get this to work?

The error I get is as follows:

An object reference is required to access non-static member `UnityEngine.MonoBehaviour.StartCoroutine(System.Collections.IEnumerator)'

Upvotes: 0

Views: 793

Answers (1)

Roberto
Roberto

Reputation: 11953

The problem actually doesn't have anything to do with coroutines.

It happens because you are trying to call two instance methods from a static method. That is, DownloadAndCache and StartCoroutine are instance methods, they are not static so they need an instance of its class Foo to execute.

DownloadAndCache could be static, so you wouldn't need an instance, but you won't get away without a MonoBehaviour instance to call StartCoroutine.

Upvotes: 1

Related Questions