You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Unity RestClient包下载图片时出现“Specified cast is not valid”错误求排查

解决RestClient下载图片时“Specified cast is not valid”的错误

你遇到的类型转换错误,核心原因是没有明确指定使用DownloadHandlerTexture作为下载处理器。

默认情况下,RestClient不会自动用DownloadHandlerTexture处理图片下载,你代码里注释掉了DownloadHandler的设置,导致res.Request.downloadHandler的实际类型不是DownloadHandlerTexture,强行做类型转换就会抛出“Specified cast is not valid”错误。

修改方案:

取消注释并调整DownloadHandler的设置,指定使用DownloadHandlerTexture(而非原来的DownloadHandlerFile,因为你需要直接获取Texture而非保存文件):

public void DownloadImage(string fileUrl, string name)
{
    RestClient.Get(new RequestHelper {
        Uri = fileUrl,
        DownloadHandler = new DownloadHandlerTexture(), // 指定为Texture下载处理器
        Method = "GET",
        DefaultContentType = true,
        EnableDebug = true,
    }).Then(res =>
    {
        Texture2D tex = ((DownloadHandlerTexture)res.Request.downloadHandler).texture;
        
        Sprite sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(tex.width / 2, tex.height / 2));
        if (img != null)
        {
            img.overrideSprite = sprite;
            img.preserveAspect = true;
        }
        
    }).Catch(err => {
        Debug.Log(err.Message);
        Debug.Log("url: " + fileUrl);
    });
}

补充说明:

设置DownloadHandlerTexture后,RestClient会直接将下载的图片数据解析为Texture2D,此时类型转换就能正常执行。另外要确认目标URL返回的是有效的图片资源,避免因资源损坏或格式不支持导致后续Sprite创建失败。

内容的提问来源于stack exchange,提问作者Minhaj Javed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 23:30:20