Unity webgl读取streamingAssetsPath文件夹txt

这篇博客详细介绍了在Unity中如何通过StreamingAssets目录读取配置文件、图片和音频文件。提供了静态类StreamingAssetPathConfigReader的三个静态方法,分别用于读取文本、图片和音频数据,并通过UnityAction回调传递结果。示例代码展示了如何在Unity编辑器中使用这些方法加载和显示资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Events;
using System.IO;


public static class StreamingAssetPathConfigReader
{

    /// <summary>
    /// 读取StreamingAsset中的配置文件
    /// </summary>
    /// <param name="configName"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public static IEnumerator TextReader(string configName, UnityAction<string> action = null)
    {
        string path;
#if UNITY_WIN_STANDALONE || UNITY_IPHONE &&!UNITY_EDITOR
        path ="file://"+ Application.streamingAssetsPath + configName;
#else 
        path = Application.streamingAssetsPath + "/" + configName;
#endif
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(path);
        yield return unityWebRequest.SendWebRequest();

        if (unityWebRequest.error != null)
            Debug.Log(unityWebRequest.error);
        else
        {
            string content = unityWebRequest.downloadHandler.text;
            if (action != null)
                action(content);
        }
    }


    /// <summary>
    /// 读取streamingAsset中的图片
    /// </summary>
    /// <param name="mediaName"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public static IEnumerator TextureReader(string  mediaName,UnityAction<Texture> action)
    {
        string path;
#if UNITY_WIN_STANDALONE || UNITY_IPHONE &&!UNITY_EDITOR
        path ="file://"+ Application.streamingAssetsPath + configName;
#else 
        path = Application.streamingAssetsPath + "/" + mediaName;
#endif

        UnityWebRequest unityWebRequest = UnityWebRequestTexture.GetTexture(path);
        yield return unityWebRequest.SendWebRequest();

       
        if (unityWebRequest.error != null)
            Debug.Log(unityWebRequest.error);
        else
        {
            byte[] bts = unityWebRequest.downloadHandler.data;
            if (action != null)
            {
                action(DownloadHandlerTexture.GetContent(unityWebRequest));
            }
        }
    }



    /// <summary>
    /// 读取streamingAsset文件夹中的多媒体(音频)
    /// </summary>
    /// <param name="mediaName"></param>
    /// <param name="action"></param>
    /// <returns></returns>

    public static IEnumerator AudioClipReader(string mediaName, UnityAction<AudioClip> action=null)
    {
        string path;
#if UNITY_WIN_STANDALONE || UNITY_IPHONE &&!UNITY_EDITOR
        path ="file://"+ Application.streamingAssetsPath + configName;
#else 
        path = Application.streamingAssetsPath + "/" + mediaName;
#endif
        FileInfo fileInfo = new FileInfo(path);
        string fileExtension = fileInfo.Extension;
        AudioType audioType;

        switch (fileExtension)
        {
            case ".mp3":
                audioType = AudioType.MPEG;
                break;
            case ".ogg":
                audioType = AudioType.OGGVORBIS;
                break;
            case ".wav":
                audioType = AudioType.WAV;
                break;
            case ".aiff":
                audioType = AudioType.AIFF;
                break;
            default:
                audioType = AudioType.MPEG;
                break;
        }

        UnityWebRequest unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(path, audioType);
        yield return unityWebRequest.SendWebRequest();

        
        if (unityWebRequest.error != null)
            Debug.Log(unityWebRequest.error);
        else
        {
            if (action != null)
                action(DownloadHandlerAudioClip.GetContent(unityWebRequest));
        }
    }
}


using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PathDebug : MonoBehaviour
{
    public GUISkin guiSkin;
    public RawImage rawImage;
    public AudioSource audioSource;
    string s = "";

    void OnGUI()
    {
        GUI.skin = guiSkin;
        GUI.Label(new Rect(100, 0, Screen.width, Screen.height), s);


        if (GUI.Button(new Rect(0, 0, 100, 50), "LoadCsv"))
            StartCoroutine(StreamingAssetPathConfigReader.TextReader("config.csv", ShowCsv));
        if (GUI.Button(new Rect(0, 50, 100, 50), "LoadTxt"))
            StartCoroutine(StreamingAssetPathConfigReader.TextReader("Test.txt", ShowTxt));
        if (GUI.Button(new Rect(0, 100, 100, 50), "LoadJson"))
            StartCoroutine(StreamingAssetPathConfigReader.TextReader("Test.json", ShowJson));

        if (GUI.Button(new Rect(0, 150, 100, 50), "ShowImage"))
            StartCoroutine(StreamingAssetPathConfigReader.TextureReader("Picture.png", ShowTexture));

        if (GUI.Button(new Rect(0, 200, 100, 50), "PlayerAudio"))
            StartCoroutine(StreamingAssetPathConfigReader.AudioClipReader("audio.wav", AudioPlay));

    }


    private void WriteText(string content)
    {
        this.s += content;
    }

    /// <summary>
    /// 读取csv文件
    /// </summary>
    /// <param name="s"></param>
    private void ShowCsv(string s)
    {
        this.s = s;
    }


    /// <summary>
    /// 读取txt文件
    /// </summary>
    /// <param name="s"></param>
    private void ShowTxt(string s)
    {
        print("----" + s);
        string[] content = s.Split('\n');
        List<string> line = new List<string>();
        for (int i = 0; i < content.Length; i++)
        {
            line.Add(content[i]);
        }

        List<TxtMessage> txtMessages = new List<TxtMessage>();

        TxtMessage currentLine = new TxtMessage();
        for (int i = 0; i < line.Count; i++)
        {
            string key = line[i].Split(':')[0];
            string value = line[i].Split(':')[1];
            currentLine.key = key;
            currentLine.value = value;
            txtMessages.Add(currentLine);

        }

        Debug.Log(txtMessages[0].value);
        if (txtMessages[0].key.Equals("信息是否保密"))
            if (txtMessages[0].value.Trim().Equals("是"))
            {
                this.s = "该用户信息保密,无法访问";
            }

            else
            {
                this.s = "";
                for (int i = 1; i < content.Length; i++)
                {
                  this.s += content[i] + "\n";
                }
            }
               
    }


    /// <summary>
    /// 读取json文件
    /// </summary>
    /// <param name="s"></param>
    private void ShowJson(string s)
    {
        //json格式是utf-8 不带bom功能  ,不然会报错
        JsonMessage jsonMessage = JsonUtility.FromJson<JsonMessage>(s);
        this.s = string.Format("{0}"+jsonMessage.name+"\n","用户名: ");
        this.s += string.Format("{0}" + jsonMessage.age+"\n","年龄: ");
        this.s += string.Format("{0}" + jsonMessage.sex+"\n","性别: ");
    }




    private void ShowTexture(Texture texture)
    {
        rawImage.texture = texture;
    }

    private void AudioPlay(AudioClip audioClip)
    {
        audioSource.clip = audioClip;
        audioSource.Play();
    }
}



/// <summary>
/// Txt信息文档
/// </summary>
public struct TxtMessage
{
    public string key;
    public string value;

}


/// <summary>
/// json文件信息
/// </summary>
[System.Serializable]
public struct JsonMessage
{
    public string name;
    public double age;
    public string sex;
}

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、

 private void Awake()
    {
        StartCoroutine(StreamingAssetPathConfigReader.TextReader("Config.txt", ShowTxt));
    }

    private void ShowTxt(string s)
    {
        lineArray = s.Split('\r');
    }

### 实现 Unity WebGL 读取 CSV 文件 在 Unity WebGL读取 `StreamingAssets` 路径下的 CSV 文件可以通过异步加载的方式完成。对于不同平台,路径处理方式有所不同,在 WebGL 平台下需特别注意资源打包与访问方法。 #### 使用 WWW 或者 UnityWebRequest 加载 StreamingAssets 下的文件 考虑到 WebGL 的特殊性,直接通过本地路径访问不可行,应采用 URL 方式获取资源。下面展示一段用于从 `StreamingAssets` 获取并解析 CSV 数据的 C# 方法: ```csharp using System.Collections; using UnityEngine.Networking; private IEnumerator LoadCsvFromWebGL() { string path = "file://" + Application.streamingAssetsPath + "/questions.csv"; #if UNITY_WEBGL && !UNITY_EDITOR path = Application.streamingAssetsPath + "/questions.csv"; // 对于WebGL, 不加前缀 #endif using (UnityWebRequest www = UnityWebRequest.Get(path)) { yield return www.SendWebRequest(); if(www.result != UnityWebRequest.Result.Success) { Debug.LogError("Failed to load csv file."); } else { ProcessCSVData(www.downloadHandler.text); } } } /// <summary> /// 解析CSV数据到题目列表中 /// </summary> /// <param name="csvContent">CSV内容字符串</param> private void ProcessCSVData(string csvContent) { char[] delimiters = new char[] { ',', '\n' }; foreach(var line in csvContent.Split(delimiters)) { // 假设每行为一道题目的描述,可根据实际格式调整此部分逻辑 AddQuestion(line.Trim()); } } ``` 上述代码展示了如何利用 `UnityWebRequest` 来请求位于 `StreamingAssets` 文件夹中的 CSV 文件,并将其内容传递给负责进一步处理的方法[^1]。 为了确保兼容性和性能考虑,建议将 CSV 文件放置于 `StreamingAssets` 文件夹内,并按照以上所示流程操作。此外,还需确认构建设置已正确配置以包含这些静态资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奇大可

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值