Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将我的代码切换到UnityWebRequest以便下载进度正常?_C#_Unity3d - Fatal编程技术网

C# 如何将我的代码切换到UnityWebRequest以便下载进度正常?

C# 如何将我的代码切换到UnityWebRequest以便下载进度正常?,c#,unity3d,C#,Unity3d,下面的代码下载我的app.apk并安装它,同时在TextDebug中跟踪下载进度。我正试图切换到UnityWebRequest,但是downloadprogress在TextDebug上没有显示 private IEnumerator downLoadFromServer() { string url = "https://example.com/app.apk"; string savePath = Path.Combine(Application.persistentD

下面的代码下载我的
app.apk
并安装它,同时在
TextDebug
中跟踪
下载进度。我正试图切换到
UnityWebRequest
,但是
downloadprogress
TextDebug
上没有显示

private IEnumerator downLoadFromServer()
{

    string url = "https://example.com/app.apk";


    string savePath = Path.Combine(Application.persistentDataPath, "data");
    savePath = Path.Combine(savePath, "app.apk");

    Dictionary<string, string> header = new Dictionary<string, string>();
    string userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36";
    header.Add("User-Agent", userAgent);
    header["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("test:test"));
    WWW theWWW = new WWW(url, null, header);


    while (!theWWW.isDone)
    {
        //Must yield below/wait for a frame
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Progress: " + theWWW.progress;
        yield return null;
    }

    byte[] yourBytes = theWWW.bytes;

    GameObject.Find("TextDebug").GetComponent<Text>().text = "Done downloading. Size: " + yourBytes.Length;


    //Create Directory if it does not exist
    if (!Directory.Exists(Path.GetDirectoryName(savePath)))
    {
        Directory.CreateDirectory(Path.GetDirectoryName(savePath));
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Created Dir";
    }

    try
    {
        //Now Save it
        System.IO.File.WriteAllBytes(savePath, yourBytes);
        Debug.Log("Saved Data to: " + savePath.Replace("/", "\\"));
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Saved Data";
    }
    catch (Exception e)
    {
        Debug.LogWarning("Failed To Save Data to: " + savePath.Replace("/", "\\"));
        Debug.LogWarning("Error: " + e.Message);
        GameObject.Find("TextDebug").GetComponent<Text>().text = "Error Saving Data";
    }

    //Install APK
    installApp(savePath);
    }
}
private IEnumerator下载自服务器()
{
字符串url=”https://example.com/app.apk";
字符串savePath=Path.Combine(Application.persistentDataPath,“data”);
savePath=Path.Combine(savePath,“app.apk”);
字典头=新字典();
string userAgent=“Mozilla/5.0(Windows NT 10.0;WOW64)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/55.0.2883.87 Safari/537.36”;
header.Add(“用户代理”,userAgent);
header[“Authorization”]=“Basic”+System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(“test:test”);
WWW theWWW=newwww(url,null,header);
而(!www.isDone)
{
//必须在下方屈服/等待一帧
GameObject.Find(“TextDebug”).GetComponent().text=“Progress:+theWWW.Progress;
收益返回空;
}
byte[]yourBytes=www.bytes;
GameObject.Find(“TextDebug”).GetComponent().text=“下载完毕。大小:”+yourBytes.Length;
//创建不存在的目录
如果(!Directory.Exists(Path.GetDirectoryName(savePath)))
{
CreateDirectory(Path.GetDirectoryName(savePath));
GameObject.Find(“TextDebug”).GetComponent().text=“Created Dir”;
}
尝试
{
//现在保存它
System.IO.File.writealBytes(存储路径,yourBytes);
Debug.Log(“将数据保存到:“+savePath.Replace”(“/”,“\\”));
GameObject.Find(“TextDebug”).GetComponent().text=“保存的数据”;
}
捕获(例外e)
{
Debug.LogWarning(“未能将数据保存到:”+savePath.Replace(“/”,“\\”));
Debug.LogWarning(“错误:+e.Message”);
GameObject.Find(“TextDebug”).GetComponent().text=“保存数据时出错”;
}
//安装APK
installApp(保存路径);
}
}
最后一条中也有注释

Unity会自动设置
用户代理
标题,不建议将其设置为自定义值

//最好已经通过Inspector引用了!
[SerializeField]私有文本progressText;
私人空间()
{
//你应该尽可能避免找!
//如果你真的想/需要使用Find
//你真的只想做一次!
如果(!progressText)progressText=GameObject.Find(“TextDebug”).GetComponent();
}
私有IEnumerator从服务器()下载
{  
变量url=”https://example.com/app.apk"; 
var savePath=Path.Combine(Application.persistentDataPath,“data”,“app.apk”);
使用(var uwr=newunityWebRequest.Get(url))
{
SetHeader(“Authorization”,“Basic”+System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(“test:test”));
uwr.SendWebRequest();
而(!uwr.isDone)
{
progressText.text=$“进度:{uwr.downloadProgress:P}”;
收益返回空;
}
var yourBytes=uwr.downloadHandler.data;
progressText.text=$“下载完成。大小:{yourBytes.Length}”;
//创建不存在的目录
var directoryName=Path.GetDirectoryName(savePath);
如果(!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
progressText.text=“已创建目录”;
}
尝试
{
//现在保存它
System.IO.File.writealBytes(存储路径,yourBytes);
Debug.Log(“将数据保存到:“+savePath.Replace”(“/”,“\\”));
progressText.text=“保存的数据”;
}
捕获(例外e)
{
Debug.LogWarning(“未能将数据保存到:”+savePath.Replace(“/”,“\\”));
Debug.LogWarning(“错误:+e.Message”);
progressText.text=“保存数据时出错”;
}
}
//安装APK
installApp(保存路径);
}


注意:在智能手机上输入,但我希望想法变得清晰

而不是新的WWW,也许可以使用新的UnityWebRequest?UnityWebRequest有很好的文档记录
// Better would be to reference this already via the Inspector!
[SerializeField] private Text progressText;

private void Awake ()
{
    // You should avoid Find whenever possible!
    // If you really want/need to use Find at all
    // you really want to do it only ONCE!
    if(! progressText) progressText = GameObject.Find("TextDebug").GetComponent<Text>();
}

private IEnumerator downLoadFromServer()
{  
    var url = "https://example.com/app.apk"; 
    var savePath = Path.Combine(Application.persistentDataPath, "data", "app.apk");              

    using (var uwr = new UnityWebRequest.Get(url))
    {
        uwr.SetHeader("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("test:test")));
        uwr.SendWebRequest();

        while (!uwr.isDone)
        {
            progressText.text = $"Progress: {uwr.downloadProgress:P}";
            yield return null;
        }

        var yourBytes = uwr.downloadHandler.data;

        progressText.text = $"Done downloading. Size: {yourBytes.Length}";

        //Create Directory if it does not exist
        var directoryName = Path.GetDirectoryName(savePath);
        if (!Directory.Exists(directoryName))
        {
             Directory.CreateDirectory(directoryName);
            progressText.text = "Created Dir";
        }

        try
        {
            //Now Save it
            System.IO.File.WriteAllBytes(savePath, yourBytes);
            Debug.Log("Saved Data to: " + savePath.Replace("/", "\\"));
            progressText.text = "Saved Data";
        }
        catch (Exception e)
        {
            Debug.LogWarning("Failed To Save Data to: " + savePath.Replace("/", "\\"));
            Debug.LogWarning("Error: " + e.Message);
            progressText.text = "Error Saving Data";
        }
    }

    //Install APK
    installApp(savePath);
}