新人报到!作为新人最近喜欢上用配置文件来封装可变化部分的代码,以配置文件形式动态调用代码。但是最近碰到个问题,一直困扰我,因为www被弃用了,而UnityWebRequest又不熟悉。经过思考和研究算是攻克了个小知识点特来分享。
1、往常大家都习惯WWW加载配置文件,但是Unity已经弃用了www网络请求api,。
2、相比大家应该都在用UnityWebRequest加载资源:但它却是协程调用,有延迟导致后面需要配置文件的代码无法正常获取【我的代码用协程老是报错报空,就是因为协程那么几帧的延迟】。
IEnumerator Send(string url)
{
UnityWebRequest request=UnityWebRequest.Get(url);
yield return request.SendWebRequest();
if (request.isHttpError || request.isNetworkError)
{
UnityEngine.Debug.Log(request.error);
}
else
{
UnityEngine.Debug.Log(request.downloadHandler.text);
}
3、我对代码进行了修改,用循环体来卡主服务器下载进度结束后立即使用配置文件资源。
void Start()
{
GetAssetBundle();
print("检查是否在Debug后面调用" + request.downloadHandler.text);
}
UnityWebRequest request;
void GetAssetBundle()
{
string path = Path.Combine(Application.streamingAssetsPath + "/" + "A1_1.txt");
request = UnityWebRequest.Get(path);
request.SendWebRequest();
while (true)
{
if (request.isHttpError || request.isNetworkError)
{
UnityEngine.Debug.Log(request.error);
return;
}
if(request.downloadProgress == 1)
{
UnityEngine.Debug.Log("循环体内读取"+request.downloadHandler.text);
return;
}
}
}
最后调试的结果如图。