大家知道streamingAssetsPath目錄下的文件讀取在android平臺下或者ios下是不能直接用File的API,需要用www或者unitywebrequest類讀寫。大部分網上的採用的方法是通過分平臺的方式。例如
下面爲大家介紹一種相對比較簡單的方式解決streamingAssetsPath文件讀取
public class GameMain : MonoBehaviour
{
private void Awake()
{
var filePath = Application.streamingAssetsPath + "/MultiLanguage/Language.json";
if (File.Exists(filePath))
{
var strContent = File.ReadAllText(filePath);
Debug.LogError(strContent);
}
else if (ShouldPathUseWebRequest(filePath))
{
var m_RequestOperation =
new UnityWebRequest(filePath, UnityWebRequest.kHttpVerbGET, new DownloadHandlerBuffer(), null)
.SendWebRequest();
m_RequestOperation.completed += RequestOperation_completed;
}
else
{
Debug.LogError(string.Format("Invalid path in RawDataProvider: '{0}'.", filePath));
}
}
private void RequestOperation_completed(AsyncOperation op)
{
var webOp = op as UnityWebRequestAsyncOperation;
object result = null;
Exception exception = null;
if (webOp != null)
{
var webReq = webOp.webRequest;
if (string.IsNullOrEmpty(webReq.error))
{
var text = webReq.downloadHandler.text;
Debug.LogError(text);
}
else
{
Debug.LogError(string.Format(
"RawDataProvider unable to load from url {0}, result='{1}'.", webReq.url, webReq.error));
}
}
else
{
Debug.LogError("RawDataProvider unable to load from unknown url.");
}
}
private bool ShouldPathUseWebRequest(string path)
{
return !string.IsNullOrEmpty(path) && path.Contains("://");
}