Unity中常用的几种读取本地文件方式

文章介绍了在Unity中使用UnityWebRequest、StreamReader和FileStream三种方式从本地StreamingAssets文件夹读取Json文件的方法,包括针对不同平台的路径判断。

使用的命名空间如下

using LitJson;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

1、通过UnityWebRequest获取本地StreamingAssets文件夹中的Json文件

      /// <summary>
    /// 通过UnityWebRequest获取本地StreamingAssets文件夹中的Json文件
    /// </summary>
    /// <param name="fileName">文件名称</param>
    /// <returns></returns>
    public string UnityWebRequestJsonString(string fileName)
    {
        string url;

        #region 分平台判断 StreamingAssets 路径
        //如果在编译器 或者 单机中  ……
#if UNITY_EDITOR || UNITY_STANDALONE

        url = "file://" + Application.dataPath + "/StreamingAssets/" + fileName;
        //否则如果在Iphone下……
#elif UNITY_IPHONE

            url = "file://" + Application.dataPath + "/Raw/"+ fileName;
            //否则如果在android下……
#elif UNITY_ANDROID
            url = "jar:file://" + Application.dataPath + "!/assets/"+ fileName;
#endif
        #endregion
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.SendWebRequest();//读取数据
        while (true)
        {
            if (request.downloadHandler.isDone)//是否读取完数据
            {
                return request.downloadHandler.text;
            }
        }
    }
```
View Code

2、通过UnityWebRequest和StreamReader读取本地StreamingAssets文件夹中的Json文件

      /// <summary>
    /// 通过UnityWebRequest获取本地StreamingAssets文件夹中的Json文件
    /// </summary>
    /// <param name="fileName">文件名称</param>
    /// <returns></returns>
    public string UnityWebRequestJsonString(string fileName)
    {
        string url;

        #region 分平台判断 StreamingAssets 路径
        //如果在编译器 或者 单机中  ……
#if UNITY_EDITOR || UNITY_STANDALONE

        url = "file://" + Application.dataPath + "/StreamingAssets/" + fileName;
        //否则如果在Iphone下……
#elif UNITY_IPHONE

            url = "file://" + Application.dataPath + "/Raw/"+ fileName;
            //否则如果在android下……
#elif UNITY_ANDROID
            url = "jar:file://" + Application.dataPath + "!/assets/"+ fileName;
#endif
        #endregion
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.SendWebRequest();//读取数据
        while (true)
        {
            if (request.downloadHandler.isDone)//是否读取完数据
            {
                return request.downloadHandler.text;
            }
        }
    }
```
View Code

 3、通过StreamReader读取本地StreamingAssets文件夹中的Json文件 

      /// <summary>
    /// 通过UnityWebRequest获取本地StreamingAssets文件夹中的Json文件
    /// </summary>
    /// <param name="fileName">文件名称</param>
    /// <returns></returns>
    public string UnityWebRequestJsonString(string fileName)
    {
        string url;

        #region 分平台判断 StreamingAssets 路径
        //如果在编译器 或者 单机中  ……
#if UNITY_EDITOR || UNITY_STANDALONE

        url = "file://" + Application.dataPath + "/StreamingAssets/" + fileName;
        //否则如果在Iphone下……
#elif UNITY_IPHONE

            url = "file://" + Application.dataPath + "/Raw/"+ fileName;
            //否则如果在android下……
#elif UNITY_ANDROID
            url = "jar:file://" + Application.dataPath + "!/assets/"+ fileName;
#endif
        #endregion
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.SendWebRequest();//读取数据
        while (true)
        {
            if (request.downloadHandler.isDone)//是否读取完数据
            {
                return request.downloadHandler.text;
            }
        }
    }
```
View Code

 4、通过FileStream读取本地StreamingAssets文件夹中的文件

    /// <summary>
    /// 通过FileStream读取本地StreamingAssets文件夹中的文件
    /// </summary>
    /// <param name="jsonName"></param>
    /// <returns></returns>
    public string GetAllFileInfos(string jsonName)
    {
        string jsonPath = Application.streamingAssetsPath + "/" + jsonName;
        try
        {
            using (FileStream fs = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
            {
                fs.Seek(0, SeekOrigin.Begin);
                var bytes = new byte[fs.Length];
                fs.Read(bytes, 0, (int)fs.Length);
                string jsonData = Encoding.UTF8.GetString(bytes);
                fs.Flush();
                fs.Dispose();
                fs.Close();
                return jsonData;
            }
            //Debug.Log("所有文件资源信息Assets下文件夹数量:" + fileInfos.Count);
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message);
            Debug.LogError("文件读取异常:" + jsonPath);
            return string.Empty;
        }
    }
View Code

参考资源:https://www.cnblogs.com/unity3ds/p/11742487.html](https://www.cnblogs.com/unity3ds/p/11742487.html

转载链接:Unity 读取Json常用的几种方式_unity读取json_科幻之眼的博客-CSDN博客

Unity开发的抖音小游戏中读取本地JSON文件,可参考以下几种常见方法: ### 使用 `UnityWebRequest` 读取 利用 `UnityWebRequest` 可以方便地从本地文件系统读取JSON文件。以下是示例代码: ```csharp using UnityEngine; using UnityEngine.Networking; using System.Collections; public class ReadLocalJSON : MonoBehaviour { IEnumerator Start() { // 假设JSON文件在StreamingAssets目录下 string filePath = Application.streamingAssetsPath + "/example.json"; UnityWebRequest request = UnityWebRequest.Get(filePath); yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.Success) { string jsonData = request.downloadHandler.text; Debug.Log(jsonData); // 在这里可以进行JSON数据的解析 } else { Debug.LogError("Error: " + request.error); } } } ``` ### 使用 `File.ReadAllText` 读取 如果是在PC或编辑器环境下,也可以使用 `File.ReadAllText` 方法直接读取文件内容,示例如下: ```csharp using UnityEngine; using System.IO; public class ReadJSONFile : MonoBehaviour { void Start() { string filePath = Application.streamingAssetsPath + "/example.json"; if (File.Exists(filePath)) { string jsonData = File.ReadAllText(filePath); Debug.Log(jsonData); // 解析JSON数据 } else { Debug.LogError("File not found: " + filePath); } } } ``` ### 解析JSON数据 读取到JSON字符串后,若要将其转换为具体的对象,可以使用 `JsonUtility`,示例如下: ```csharp [System.Serializable] public class ExampleData { public string name; public int age; } // 在读取到JSON字符串后进行解析 string jsonData = ...; // 假设这是读取到的JSON字符串 ExampleData data = JsonUtility.FromJson<ExampleData>(jsonData); Debug.Log("Name: " + data.name + ", Age: " + data.age); ```
Unity读取本地音频有多种方法,以下是几种常见的实现方式: ### 使用UnityWebRequestMultimedia(支持MP3格式) unity新版的UnityWebRequestMultimedia已经支持了MP3格式。以下是示例代码: ```csharp using UnityEngine; using UnityEngine.Networking; public class LocalAudioLoader : MonoBehaviour { public AudioSource audioSource; private IEnumerator LoadMusic(string filepath) { filepath = "file://" + filepath; using (var uwr = UnityWebRequestMultimedia.GetAudioClip(filepath, AudioType.MPEG)) { yield return uwr.SendWebRequest(); if (uwr.isNetworkError) { Debug.LogError(uwr.error); } else { AudioClip clip = DownloadHandlerAudioClip.GetContent(uwr); audioSource.clip = clip; } } } void Start() { // 调用加载方法,可根据实际情况修改文件路径 StartCoroutine(LoadMusic("/storage/emulated/0/a.mp3")); StartCoroutine(LoadMusic("D:/a.mp3")); } } ``` 这种方法使用`UnityWebRequestMultimedia.GetAudioClip`来获取音频剪辑,支持MP3格式,适用于大多数Unity项目[^2]。 ### 使用NAudio.dll进行数据流转换 可以直接通过NAudio.dll的数据流进行转换。示例代码如下: ```csharp using System.Collections; using System.IO; using NAudio.Wave; using UnityEngine; public class MusicLoad : MonoBehaviour { public AudioSource Source; private void Start() { StartCoroutine(LoadSongCoroutine()); } private IEnumerator LoadSongCoroutine() { string path = "X:/...Life.mp3"; // mp3文件,文件路径 string url = string.Format("file://{0}", path); WWW www = new WWW(url); yield return www; Source.clip = NAudioPlayer.FromMp3Data(www.bytes); Source.Play(); } } ``` 此方法借助NAudio.dll将MP3数据转换为Unity可使用的音频剪辑,适用于需要对音频进行更复杂处理的场景[^3]。 ### 使用UnityWebRequestMultimedia动态加载(支持WAV和MP3) 使用`UnityWebRequestMultimedia.GetAudioClip`动态加载本地音频,支持WAV和MP3格式。示例代码如下: ```csharp using UnityEngine; using UnityEngine.Networking; public class DynamicAudioLoader : MonoBehaviour { public AudioSource audioSource; public string url; IEnumerator LoadVoiceSync() { using (UnityWebRequest webRequest = UnityWebRequestMultimedia.GetAudioClip(url, AudioType.WAV | AudioType.MPEG)) { ((DownloadHandlerAudioClip)webRequest.downloadHandler).streamAudio = true; yield return webRequest.SendWebRequest(); while (!webRequest.isDone) { yield return null; } if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError) { Debug.Log(webRequest.error.ToString()); yield return webRequest.error; } else { var audioClip = DownloadHandlerAudioClip.GetContent(webRequest); audioSource.clip = audioClip; audioSource.Play(); } } } void Start() { // 调用加载方法,可根据实际情况修改url StartCoroutine(LoadVoiceSync()); } } ``` 该方法通过`UnityWebRequestMultimedia.GetAudioClip`动态加载本地音频,支持WAV和MP3格式,并且可以处理网络错误和协议错误[^4]。
### Unity读取关卡文件的实现方法 在 Unity 中,关卡文件通常以场景(Scene)的形式存在。通过 `SceneManager` 类可以加载这些场景文件。以下是几种常见的读卡文件实现方式。 #### 1. 使用 `SceneManager.LoadScene` Unity 提供了 `SceneManager` 类来管理场景的加载、卸载和切换。以下是一个简单的示例代码,展示如何通过脚本加载指定的关卡文件[^2]: ```csharp using UnityEngine; using UnityEngine.SceneManagement; public class LoadLevelExample : MonoBehaviour { public void LoadLevelByName(string levelName) { // 加载指定名称的关卡 SceneManager.LoadScene(levelName); } public void LoadLevelByIndex(int levelIndex) { // 加载指定索引的关卡 SceneManager.LoadScene(levelIndex); } } ``` #### 2. 从 StreamingAssets 文件夹读取关卡文件 如果关卡文件存储在 `StreamingAssets` 文件夹中,可以通过文件流读取并动态加载场景。以下是实现代码[^1]: ```csharp using UnityEngine; using System.IO; using UnityEditor; using System.Collections; public class LoadLevelFromStreamingAssets : MonoBehaviour { public IEnumerator LoadLevelFromStreamingAssetsAsync(string levelName) { string path; #if UNITY_ANDROID path = Path.Combine(Application.streamingAssetsPath, levelName + ".unity"); #else path = Path.Combine(Application.streamingAssetsPath, levelName); #endif if (File.Exists(path)) { WWW www = new WWW("file://" + path); // 在 Android 上需要使用 WWW 来读取文件 yield return www; if (string.IsNullOrEmpty(www.error)) { AssetBundle bundle = www.assetBundle; Scene scene = bundle.LoadAsset<Scene>(levelName); SceneManager.LoadScene(scene.name); } else { Debug.LogError("Error loading level: " + www.error); } } else { Debug.LogError("File not found: " + path); } } } ``` #### 3. 从服务器下载并加载关卡文件 如果关卡文件存储在远程服务器上,可以通过网络请求下载文件并加载。以下是一个示例代码[^3]: ```csharp using UnityEngine; using System.Collections; using UnityEngine.Networking; public class LoadLevelFromServer : MonoBehaviour { public IEnumerator LoadLevelFromServerAsync(string url, string levelName) { using (UnityWebRequest www = UnityWebRequest.Get(url)) { yield return www.SendWebRequest(); if (www.result != UnityWebRequest.Result.Success) { Debug.LogError("Failed to download level: " + www.error); } else { string filePath = Path.Combine(Application.persistentDataPath, levelName + ".unity"); File.WriteAllBytes(filePath, www.downloadHandler.data); // 加载本地保存的关卡文件 StartCoroutine(LoadLevelFromStreamingAssetsAsync(levelName)); } } } } ``` ### 注意事项 - 在 Android 平台上,`Application.streamingAssetsPath` 指向的是 APK 内部的资源路径,因此需要使用 `WWW` 或 `UnityWebRequest` 来读取文件[^1]。 - 如果需要频繁加载和卸载关卡,建议使用异步加载方法 `SceneManager.LoadSceneAsync`,以避免阻塞主线程[^2]。 ---
### Unity 中加载预制体的方法 在 Unity 中,可以通过多种方式来加载预制体。以下是几种常见的方法。 #### 使用 `Resources.Load` 方法加载预制体 当预制体存储在 Resources 文件夹下时,可以利用 `Resources.Load` 函数轻松地获取并实例化预制体对象[^4]: ```csharp // 定义路径以及加载预制体 string path = "Prefabs/MyPrefab"; GameObject prefab = Resources.Load<GameObject>(path); if (prefab != null) { // 在指定位置和旋转角度实例化该预制体 Instantiate(prefab, new Vector3(0, 0, 0), Quaternion.identity); } else { Debug.LogError("未能找到预制体:" + path); } ``` 这种方法简单易用,适合快速原型设计阶段;然而,在正式项目里不推荐过度依赖此法因为难以管理资源文件结构,并且增加了编译后的 APK/IPA 大小。 #### 利用 AssetBundle 动态加载预制体 对于大型游戏而言,采用 AssetBundles 来分发额外的内容是一种有效策略。这种方式允许开发者按需下载特定资产而无需重新安装整个应用程序[^3]。 构建好 AssetBundle 后,可通过下面的方式加载其中包含的预制体: ```csharp IEnumerator LoadAssetFromBundle() { string bundlePath = System.IO.Path.Combine(Application.streamingAssetsPath, "mybundle"); using (var assetBundle = AssetBundle.LoadFromFile(bundlePath)) { if (assetBundle == null) { yield break; } var prefabName = "MyPrefab"; GameObject prefab = assetBundle.LoadAsset<GameObject>(prefabName); if (prefab != null) { Instantiate(prefab, transform.position, transform.rotation); } else { Debug.LogError($"未发现名为 {prefabName} 的预制体."); } } } ``` 上述代码片段展示了如何从本地磁盘读取 AssetBundle 并从中提取所需的预制体进行实例化操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值