c# - InvalidCastException: Specified cast is not valid 尝试从 url 获取图像时出错
问题描述
我正在尝试从中获取图像纹理
IEnumerator GetRequest1(string uri)
{
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
yield return webRequest.SendWebRequest();
img = ((DownloadHandlerTexture)webRequest.downloadHandler).texture;
}
}
并将其传递给 GUI
void OnGUI()
{
GUILayout.BeginArea(new Rect(100, 50, 500, 500));
GUILayout.Label(img);
GUILayout.EndArea();
}
它应该在前几天工作,今天有一些修改它的命中错误,尝试了这个等等,但无法得到帮助。如果我得到提示,那就太好了。谢谢你
我在其他地方使用相同的方法,但那是完美的,在这里它的命中错误为
InvalidCastException:指定的强制转换无效。gettiles+d__25.MoveNext () (at Assets/Scripts/gettiles.cs:111)UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/导出/脚本/Coroutines.cs:17)
一个 InvalidCastException 错误 在数据的实际类型与传递的类型不匹配的情况下命中但这里是精灵到精灵
specificimage.sprite = Sprite.Create(((DownloadHandlerTexture)webRequest.downloadHandler).texture, new Rect(0, 0, 250,250).texture.height), new Vector2(0.5f, 0.5f));
解决方案
尝试这个:
using (UnityWebRequest uwr = UnityWebRequestTexture.GetTexture(uri))
{
yield return uwr.SendWebRequest();
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
img = DownloadHandlerTexture.GetContent(uwr);
specificimage.sprite =Sprite.Create(img, new Rect(0, 0, img.width, img.height), new Vector2(0.5f, 0.5f));
}
}
推荐阅读
- rust - 无法使用货物 xbuild 链接到高地址
- javascript - 错误:未捕获的 ReferenceError:使用 module.export 时未定义模块
- .net-core - 处理请求时发生未处理的异常。'/Views/Shared/_Layout.cshtml'
- spring-webflux - 使用 Vaadin Flow 实时更新 ApexChart
- ios - 如何在不影响后续设置的情况下将自己设置为委托类委托给其他对象实现委托方法?
- visual-studio-code - 如何阻止 Visual Studio Code (VSCode) 检测未保存的新文件?
- java - 使用正在复制到主文件中的 Java POI 跳过后续工作表中的第一行
- javascript - 在另一个函数内部调用函数
- c# - 以随机方式用一个单词替换字符串中的空格c#
- linux - 可以在 dash shell 或 bourne shell 中使用子字符串扩展吗?