我使用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用作全球变量。
是否可以在与我所说的相同的地方使用协程方法或从协程返回纹理值。像
pictureObj myPicture = new pictureObj();
myPicture.url = result;
myPicture.Id = cnt;
myPicture.texture = [texture from UnityWebRequest coroutine]
答案 0 :(得分:0)
据我所知,统一协同程序无法做到这一点,但是您可以使用回调函数
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));
}
}
}
答案 1 :(得分:0)
为什么不使用静态变量?您将定义放入任何已加载的脚本中
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;