Unity streamingAssetsPath文件讀取

大家知道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("://");
        }
發佈了15 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章