在我的脚本中,我希望文本bytesDownloadedText
能够更新到目前为止已下载的字节数,但它只运行一次并保持为0.如何解决此问题
private IEnumerator DownloadFile(){
WWW w = new WWW (PATH_TO_DOWNLOAD);
bytesDownloadedText.text = w.bytesDownloaded.ToString();
yield return w;
if (w.error != null) {
Debug.LogError ("Error: " + w.error);
} else {
scriptText = w.text;
filesDownloaded = true;
Debug.Log (scriptText);
}
}
修改:新代码+其他调试信息
private IEnumerator DownloadFile(){
WWW w = new WWW (PATH_TO_DOWNLOAD);
while(!w.isDone){
bytesDownloadedText.text = w.bytesDownloaded.ToString ();
Debug.Log ("Bytes Downloaded: " + w.bytesDownloaded);
yield return null;
}
Debug.Log ("Exiting while loop");
if (w.error != null) {
Debug.LogError ("Error: " + w.error);
} else {
//bytesDownloadedText.text = w.bytesDownloaded.ToString ();
scriptText = w.text;
filesDownloaded = true;
Debug.Log (scriptText);
}
}
3.Code DownloadFile
被称为
private void Start(){
StartCoroutine (DownloadFile ());
}
using UnityEngine;
public class TestScript: MonoBehaviour{
public void Update(){
if (Input.GetMouseButtonDown (0)) {
RaycastHit hit;
if (Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition),out hit)){
if (hit.transform.tag == "Destroy") {
Destroy (hit.transform.root.gameObject);
}
}
}
}
}

编辑:在线代码
<?
$scriptText = "";
$file_handle = fopen("TestScript.cs","r");
while(!feof($file_handle)){
$line = fgets($file_handle);
$scriptText = $scriptText . $line;
}
fclose($file_handle);
$size = strlen($scriptText);
header("Content-length: ".$size);
echo $scriptText;
?>
答案 0 :(得分:1)
如果您想使用WWW
属性,请不要产生bytesDownloaded
,因为这将暂停您的代码,直到WWW
返回,这使得无法读取已下载的数据量。
您必须将WWW.bytesDownloaded
置于循环中,然后使用WWW.isDone
检测何时完成WWW
,然后退出循环。在该循环内,您可以使用WWW.bytesDownloaded
显示下载的数据。最后,您必须在每个循环后等待一个帧,以便其他脚本可以执行,或者Unity将冻结,直到下载完成。
这就是代码的样子:
private IEnumerator DownloadFile()
{
WWW w = new WWW(PATH_TO_DOWNLOAD);
while (!w.isDone)
{
yield return null;
bytesDownloadedText.text = w.bytesDownloaded.ToString();
Debug.Log("Bytes Downloaded: " + w.bytesDownloaded);
}
if (w.error != null)
{
Debug.LogError("Error: " + w.error);
}
else
{
scriptText = w.text;
filesDownloaded = true;
Debug.Log(scriptText);
}
}
注意:在某些情况下bytesDownloaded
属性返回0
。这与Unity无关。这主要发生在您的服务器未发送Content-Length
标头时。
从服务器(php)发送Content-Length
标头的示例:
<?php
//String to send
$data = "Test message to send";
//Get size
$size= strlen($data);
//Set Content-length header
header("Content-length: ".$size);
//Finally, you can send the data
echo $data;
?>