首页 > 解决方案 > 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));

标签: c#imageunity3dwebrequest

解决方案


尝试这个:

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

推荐阅读