Unity StreamingAssets目录是特殊目录,该目录下的文件只读。并且在不同的平台读取方式不一样,尤其是安卓平台。下面的方法可以正确读取StreamingAssets中的文件内容
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class FileUtil
{
/// <summary>
///读取StreamingAssets中的文件
/// </summary>
/// <param name="path">StreamingAssets下的文件路径</param>
/// <returns>读取到的字符串</returns>
public static string GetTextFromStreamingAssets(string path)
{
string localPath = "";
if (Application.platform == RuntimePlatform.Android)
{
localPath = Application.streamingAssetsPath + "/" + path;
}
else
{
localPath = "file:///" + Application.streamingAssetsPath + "/" + path;
}
UnityWebRequest requrest = UnityWebRequest.Get(localPath);
var operation = requrest.SendWebRequest();
while (!operation.isDone)
{ }
if (requrest.isNetworkError || requrest.isHttpError)
{
Debug.Log(requrest.error);
return "";
}
else
{
return requrest.downloadHandler.text;
}
}
}