如何从协程中获取价值



我用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 中,但由于协程方法在我初始化对象的括号之外。我还将 pictureObj 添加到列表中,以便它是动态的,并且不能使用 myPicture 作为 gloabal 变量。

是否可以在我调用它的同一位置使用协程方法或从协程返回纹理值。 类似的东西

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

据我所知 Unity 协程做不到这一点,但是你可以像这样使用回调

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));
}
}
}

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

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;

最新更新