Unity发布WebGL之后读取StreamingAssets文件路径数据 |
您所在的位置:网站首页 › unity随机排序 › Unity发布WebGL之后读取StreamingAssets文件路径数据 |
借鉴文章 Unity打包WebGL之后保留了StreamingAssets文件夹,但是使用Application.streamingAssetsPath是无法读取到StreamingAssets文件路径的。为了能正确读取到本地StreamingAssets文件的数据,我们需要使用到UnityWebRequest类。 UnityWebRequest 由三个元素组成 UploadHandler 处理数据将数据发送到服务器的对象 DownloadHandler 从服务器接收数据的对象 UnityWebRequest 负责 HTTP通信流量控制来管理上面两个对象的对象。Uri类 System.Uri这个类,这个类可以帮助我们更好的构造uri,特别是在使用本地路径得时候,结合Path.Combine能更好的得出Uri路径。因为平台的区别,Uri路径也不同: Windows平台 file:///D:/DATA/StreamingAssets/data.json WebGl平台 http://localhost/StreamingAssets/data.json Android平台 jar:file:///data/app/xxx!/assets/data.json iOS平台 Application/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/xxx.app/Data/Raw使用Path.Combine拼接路径字符串 var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath, “data.json”)); 使用UnityWebRequest.Get读取文件 public class JsonTest : MonoBehaviour { private void Start() { StartCoroutine(GetData()); } IEnumerator GetData() { var uri = new System.Uri(Path.Combine(Application.streamingAssetsPath,"test.txt")); UnityWebRequest www = UnityWebRequest.Get(uri); yield return www.SendWebRequest(); if(www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { Debug.Log(www.downloadHandler.text); string jsonStr = www.downloadHandler.text; TestData data = JsonMapper.ToObject(jsonStr); Debug.Log("姓名:" + data.userName + "\n年龄:" + data.age); } } } [System.Serializable] public class TestData { public string userName; public int age; }测试test.txt数据: { "userName":"王武", "age":26 } |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |