Unity3D中读取CSV文件

北城以北 提交于 2020-01-29 04:19:22

直接上代码

Part1:

 1 using UnityEngine;
 2 using System.IO;
 3 using System.Collections.Generic;
 4 
 5 public class CSV
 6 {
 7     static CSV csv;
 8     public List<string[]> m_ArrayData;
 9     public static CSV GetInstance()
10     {
11         if (csv == null)
12         {
13             csv = new CSV();
14         }
15         return csv;
16     }
17     private CSV() { m_ArrayData = new List<string[]>(); }
18     public string GetString(int row, int col)
19     {
20         return m_ArrayData[row][col];
21     }
22     public int GetInt(int row, int col)
23     {
24         return int.Parse(m_ArrayData[row][col]);
25     }
26     public void LoadFile(string path, string fileName)
27     {
28         m_ArrayData.Clear();
29         StreamReader sr = null;
30         try
31         {
32             sr = File.OpenText(path + "//" + fileName);
33             Debug.Log("file finded!");
34         }
35         catch
36         {
37             Debug.Log("file don't finded!");
38             return;
39         }
40         string line;
41         while ((line = sr.ReadLine()) != null) 
42         {
43             m_ArrayData.Add(line.Split(','));
44         }
45         sr.Close();
46         sr.Dispose();
47     }
48 }

 Part2:

using UnityEngine;

public class FileController : MonoBehaviour
{

    // Use this for initialization
    void Start ()
    {
        CSV.GetInstance().LoadFile(Application.dataPath + "/Res", "myTest.csv");

        Debug.Log("GetString : " + CSV.GetInstance().GetString(1, 1));
        Debug.Log("GetInt : " + CSV.GetInstance().GetString(1, 2));
    }
}

补充

关于路径有4个类型:

Application.dataPath:该路径指向我们Unity编辑器的Asset文件夹

Application.persistentDataPath:该路径指向iOS和Android的沙盒路径

Application.streamingAssetsPath:streamingAsset文件夹路径,在任何平台都可以通过这个路径读取到文件夹里的内容

Application.temporaryCachePath:临时数据文件路径

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!