【Unity快速实现小功能】加载文本文件之——加载txt文件

本文介绍了在Unity中如何实现加载txt文件的详细步骤。通过创建一个utf-8编码的txt文件和使用LoadTXTFile.cs脚本,可以成功读取并显示文件内容。在运行后,控制台会显示出txt文件的文本内容。

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

问题描述:unity下实现加载txt文件、xml文件、json格式数据。

解决方案:

1)  实现unity下加载txt文件。

a.个文本格式为utf-8的txt文件,以及读取文件的 LoadTXTFile.cs脚本;

b.      LoadTXTFile脚本代码如下:

usingUnityEngine;

usingSystem.Collections;

usingSystem.IO;

 

publicclass LoadTXTFile : MonoBehaviour {

 

    //存放读取的txt文件中的内容

    private string[] _txtStr;

    void Start()

    {

        LoadTXT();

        //显示读取到的文本内容

        if(_txtStr != null &&_txtStr.Length > 0)

        {

            foreach(string str in _txtStr)

            {

                Debug.Log(str);

            }

        }

    }

 

    private void LoadTXT()

    {

        //设置文件位置,根据自己的需要进行设置

        string filePath = Application.dataPath+ "/LoadFileStudy/Resources/studyTXT.txt";

        try

        {

            //读取文件的每一行,并将每一行放入_txtStr数组中

            _txtStr =File.ReadAllLines(filePath);

        }

        catch (IOException e)

   
### 如何在 Unity加载配置文件 #### 加载 Excel 配置文件 为了在 Unity 中读取 Excel 文件的内容,可以采用一种较为复杂但是功能强大的方法——先将 Excel 转换成 CSV 或者 JSON 格式再进行读取。对于更高级的应用,则可以直接利用第三方库来解析原始的 .xlsx 文件[^2]。 ```csharp using UnityEngine; using System.IO; using Excel; // 假设已经引入了用于处理Excel的工作簿类库 public class ExcelReader : MonoBehaviour { void Start() { string filePath = Application.dataPath + "/Resources/excelFile.xlsx"; FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read); IExcelDataReader excelReader; if (filePath.EndsWith(".xls")) { // Excel 97-03 excelReader = ExcelReaderFactory.CreateBinaryReader(stream); } else if (filePath.EndsWith(".xlsx")) { // Excel 07 及以上版本 excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream); } else { throw new Exception("Unsupported file extension."); } while(excelReader.Read()) { Debug.Log($"Row: {excelReader.Row}, Column A Value: {excelReader.GetString(0)}"); } excelReader.Close(); stream.Close(); } } ``` 此代码片段展示了如何打开位于 `Assets/Resources` 文件夹下的 Excel 文档,并逐行打印出第一列的数据作为简单的演示目的。实际应用时可以根据需求调整逻辑以适应具体业务场景的需求。 #### 通过服务器加载 Text/XML/JSON 配置文件 另一种常见的做法是从远程服务器下载配置信息。这通常涉及到向 Web API 发送请求并接收响应数据的过程。下面是一个例子,它展示了一个基本的方式去获取来自 HTTP(S) URL 的文本资源,并将其存储在一个易于访问的地方比如字典中以便后续操作[^3]。 ```csharp using UnityEngine; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEngine.Networking; public class ConfigLoader : MonoBehaviour { private Dictionary<string,string> configDict = new Dictionary<string,string>(); IEnumerator LoadConfigFromServer(string url){ using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { yield return webRequest.SendWebRequest(); if(webRequest.result != UnityWebRequest.Result.Success) { Debug.LogError("Error loading configuration from server!"); }else{ ParseAndStoreConfigs(webRequest.downloadHandler.text); } } } void ParseAndStoreConfigs(string content){ var lines = Regex.Split(content,"\r\n|\n").Where(line => !string.IsNullOrWhiteSpace(line)); foreach(var line in lines){ var parts = line.Split('='); if(parts.Length==2){ configDict.Add(parts[0].Trim(),parts[1].Trim()); } } } public string GetConfigValue(string key){ return configDict.ContainsKey(key)?configDict[key]:"Not Found!"; } void Start(){ StartCoroutine(LoadConfigFromServer("http://example.com/config.txt")); } } ``` 这段脚本实现了从给定URL地址拉取纯文本格式(`key=value`)形式保存下来的键值对集合的功能;之后这些参数会被解析成内存里的字典结构供其他部分随时查询使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值