Unity3d 如何从协同程序中获取价值

Unity3d 如何从协同程序中获取价值,unity3d,Unity3d,我使用WWW加载图像的纹理 pictureObj myPicture = new pictureObj(); myPicture.url = result; myPicture.Id = cnt; WWW imgLoad = new WWW(result); myPicture.texture = imgLoad.texture; 我得到警告说WWW已经过时了。所以我开始使用UnityWebRequestTexture.GetTexture 在我查看的代码示例中,我需要启动一个协同程序,然后用

我使用WWW加载图像的纹理

pictureObj myPicture = new pictureObj();
myPicture.url = result;
myPicture.Id = cnt;
WWW imgLoad = new WWW(result);
myPicture.texture = imgLoad.texture;
我得到警告说WWW已经过时了。所以我开始使用UnityWebRequestTexture.GetTexture 在我查看的代码示例中,我需要启动一个协同程序,然后用另一种方法加载纹理

IEnumerator GetTexture(string filePath)
{
    using (UnityWebRequest req = UnityWebRequestTexture.GetTexture(filePath))
    {
        yield return req.SendWebRequest();
        if (req.isNetworkError)
        {
            Debug.Log(req.error);
        }
        else
        {
            myPicture.texture = DownloadHandlerTexture.GetContent(req); 
        }
    }
}
在我的代码中,我将纹理保存在myPicture中,但因为coroutine方法位于初始化对象的括号之外。我还将pictureObj添加到列表中,使其动态且不能使用myPicture作为gloabal变量

是否可以在我调用它的同一个位置使用协程方法,或者从协程返回纹理值。差不多

pictureObj myPicture = new pictureObj();
myPicture.url = result;
myPicture.Id = cnt;
myPicture.texture = [texture from UnityWebRequest coroutine]

据我所知,unity coroutine无法做到这一点,但您可以像这样使用回调

pictureObj myPicture = new pictureObj();
myPicture.url = result;
myPicture.Id = cnt;
StartCoroutine(GetTexture("xxx", (Texture t ) =>  { myPicture.texture = t; })); 

IEnumerator GetTexture(string filePath , System.Action<Texture> callback)
{
    using (UnityWebRequest req = UnityWebRequestTexture.GetTexture(filePath))
    {
        yield return req.SendWebRequest();
        if (req.isNetworkError)
        {
            Debug.Log(req.error);
        }
        else
        {
            callback(DownloadHandlerTexture.GetContent(req));
        }
    }
}
pictureObj myPicture=new pictureObj();
myPicture.url=结果;
myPicture.Id=cnt;
start例程(GetTexture(“xxx”,“Texture t)=>{myPicture.Texture=t;}));
IEnumerator GetTexture(字符串文件路径,System.Action回调)
{
使用(UnityWebRequest req=UnityWebRequestTexture.GetTexture(文件路径))
{
产生返回请求SendWebRequest();
如果(请求isNetworkError)
{
调试日志(请求错误);
}
其他的
{
回调(DownloadHandlerTexture.GetContent(req));
}
}
}

为什么不使用静态变量?您将定义放入任何加载的脚本中

public static class MyTexture
{
    public static Texture texture; //dont know the type of texture, so replace
}
然后在协同程序中执行以下操作:

          MyTexture.texture = DownloadHandlerTexture.GetContent(req);
然后在脚本中,您可以

          myPicture.texture = MyTexture.texture;

我可以,但我需要这个纹理,在我调用它之后,我放弃并调用web请求,如示例中所示,并在IEnumator方法中创建并填充我的myPicture对象对不起,我迷路了,你能在启动coroutine时详细说明脚本的顺序吗。。