IEnumerator yielding to the result of another IEnumerator

半腔热情 提交于 2021-01-07 05:07:18

问题


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)'


回答1:


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.



来源:https://stackoverflow.com/questions/23343978/ienumerator-yielding-to-the-result-of-another-ienumerator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!