Unity发布webgl之后读取streamingAssets中的txt文件

本文介绍了在Unity发布为webgl模式后,由于限制不能直接使用System.IO读取streamingAssets文件,改用UnityWebRequest进行远程请求并解析json内容的过程,展示了如何利用UnityWebRequestMgr进行网络请求获取文本数据。
摘要由CSDN通过智能技术生成

Unity发布webgl之后读取streamingAssets中的txt文件

Unity在发布完webgl之后就不能使用System.IO去读取文件中的内容了。需要使用请求的方式去读取。

		   //路径拼接
            var serverConfig = new System.Uri(Path.Combine(
                Application.streamingAssetsPath + @"/Config", "serverconfig.json"));

            UnityWebRequestMgr.Instance.GetText(serverConfig.ToString(), (temp) =>
            {
                if (!String.IsNullOrWhiteSpace(temp))
                {
                    serviceConfig = JsonUtility.FromJson<ServiceConfig>(temp);
 				   	Debug.Log("读取到的内容有:"+Temp);
                }
                else
                {
                    Debug.Log("加载配置文件错误");
                }
            });
    /// <summary>
    /// web请求管理器
    /// </summary>
    public class UnityWebRequestMgr : SingletonMono<UnityWebRequestMgr>
    {
        public void GetText(string url, Action<string> actionResult)
        {
            StartCoroutine(GetTextAsyn(url, actionResult));
        }
   }

SingletonMono是一个单利的class,百度上很多

        private IEnumerator GetTextAsyn(string url, Action<string> actionResult)
        {
            UnityWebRequest request = UnityWebRequest.Get(url);
            yield return request.SendWebRequest();
            string t = request.downloadHandler.text;
            if (string.IsNullOrEmpty(t)) Debug.LogError(GetType() + "GetTextAsyn()/ Get Text is error! url:" + url);
            actionResult?.Invoke(t);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值