我是在安卓平台下使用此功能,windows平台可以直接使用StreamReader来读取
public string LoadGameData(string fileName)
{
if(!File.Exists(fileName)) //判断文件是否存在
return null;
StreamReader streamReader = File.OpenText(fileName);
data = streamReader.ReadToEnd();
streamReader.Close();
return data;
}
UnityWebRequest需要使用协程加载,所以需要定义变量来进行互斥
private bool isDownloading = false; // 是否有某个协程正在下载中
获取协程返回值,因为是我明确是获取的字符串所以加了as来约束
如果不需要返回值可以直接StartCoroutine(协程名);
/// <summary>
/// 获取游戏文件数据
/// </summary>
/// <param name="fileName">文件名带路径</param>
/// <returns></returns>
public string LoadGameData(string fileName)
{
string data = "";
if (gameRoot.platform == Platform.Android)
{
IEnumerator iter = GetUnityWebRequest(fileName);
//循环赋值是因为我只会返回一次string类型数据,其他情况都是返回null,是不需要的
while (iter.MoveNext())
{
data = iter.Current as string;
}
}
if (data==null || data=="")
{
return "空";
}
return data;
}
IEnumerator GetUnityWebRequest(string fileName)
{
while (isDownloading)
{
yield return null; // 下一帧继续检测是否还有其他协程正在下载中
}
isDownloading = true; // 可以开始下载,先修改标记
string data = "";
UnityWebRequest webRequest = UnityWebRequest.Get(fileName);
yield return webRequest.SendWebRequest();
if (webRequest.isNetworkError)
{
Debug.Log(": Error: " + webRequest.error);
}
//因为第一次可能还没加载完,返回的是0没有数据,所以需要判断一下,但是如果加载不出来就会死循环,可以自己做处理,我这里暂时就不写了
while(webRequest.responseCode != 200)
{
yield return null;
}
if (webRequest.responseCode == 200)//200表示接受成功
{
data = webRequest.downloadHandler.text;
yield return data;
isDownloading = false; // 完成下载后,修改标记
}
}
参考: