Unity 读取CSV文件操作

一种webgl端使用的,一种PC端的,按需使用。(切记CSV文件转换的时候需要查看是不是UTF-8格式,要不取出来会乱码的,查看方式是用记事本打开看一下是不是,不是就另存为一下就好了)

直接上代码吧 代码如下:

c# 复制代码
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;

public class GetExcelData : MonoBehaviour
{
    public TextAsset dataname;
    public string datanameS;
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine("GetData");
        //GetListsData();
    }
    IEnumerator GetData()
    {
        List<List<string>> csvData = new List<List<string>>();
        UnityWebRequest request = UnityWebRequest.Get(Path.Combine(Application.streamingAssetsPath+"/Data/", datanameS + ".csv"));
        yield return request.SendWebRequest();
        if (request.isNetworkError ||request.isHttpError)
        {
            Debug.Log("没有连接成功");
        }
        else
        {
            Debug.Log("连接成功");       
            string[] lineArray = request.downloadHandler.text.Split("\r"[0]);

            for (int i = 0; i < lineArray.Length; i++)
            {
                //去除CSV文件里面的换行符,如果没有就不需要
                Debug.Log(Regex.Replace(lineArray[i].ToString(), @"^\n", ""));            
            }
        }
    }

    public string[][] Arrays;
    public void GetListsData()
    {
        //读取csv二进制文件  resources里面的   第一种
        TextAsset binAsset = Resources.Load(dataname.text, typeof(TextAsset)) as TextAsset;
        //放在Assets文件下面的文件,拖上去的   第二种
        //TextAsset binAsset = dataname;

        //读取每一行的内容
        string[] lineArray = binAsset.text.Split("\r"[0]);

        //创建二维数组
        Arrays = new string[lineArray.Length][];

        //把csv中的数据储存在二位数组中
        for (int i = 0; i < lineArray.Length; i++)
        {
            Arrays[i] = lineArray[i].Split(',');
        }
        //第一行 第一列的数据
      Debug.Log (Arrays[0][1].ToString());
       

    }
    // Update is called once per frame
    void Update()
    {
        
    }
}

有需要会继续补充的!!!

相关推荐
SmalBox14 小时前
03-04-架构篇-文件系统架构(IFileSystem)
unity3d·游戏开发
鑫鑫哥adam11 天前
一个 1x1 贴图,是怎么炸掉整个热更包的?
unity3d·游戏开发
Behavior12 天前
Unity 手游动态更换 App 图标 — Android 与 iOS 双端技术方案
c#·unity3d·游戏开发
SmalBox12 天前
03-03-架构篇-Runtime加载系统架构
unity3d·游戏开发
SmalBox12 天前
03-02-架构篇-Editor打包系统架构
unity3d·游戏开发
Behavior12 天前
Unity 手游 iOS Deep Link 唤醒全流程:从 URL Scheme / Universal Links 到 C# 层参数投递
c#·unity3d·游戏开发
SmalBox12 天前
03-01-架构篇-整体架构总览
unity3d·游戏开发
SmalBox12 天前
02-08-原理篇-异步加载与性能优化
unity3d·游戏开发
字节暗面12 天前
Unity AssetBundle 热更新安全排查:从 CDN 清单到本地缓存
unity3d·图片资源
SmalBox17 天前
02-07-原理篇-文件系统与跨平台适配
unity3d·游戏开发