Unity streamingAssetsPath文件读取

本文介绍了一种在Unity中解决StreamingAssetsPath目录下文件读取问题的简便方法,适用于Android和iOS平台。通过使用UnityWebRequest类替代File类API,实现跨平台文件读取,避免了直接使用File类API在移动端的限制。

大家知道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("://");
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值