大家知道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("://");
}
本文介绍了一种在Unity中解决StreamingAssetsPath目录下文件读取问题的简便方法,适用于Android和iOS平台。通过使用UnityWebRequest类替代File类API,实现跨平台文件读取,避免了直接使用File类API在移动端的限制。
3063

被折叠的 条评论
为什么被折叠?



