Unity3D中讀取CSV文件

直接上代碼編輯器

Part1:this

 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:spa

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));
    }
}

補充code

關於路徑有4個類型:blog

Application.dataPath:該路徑指向咱們Unity編輯器的Asset文件夾string

Application.persistentDataPath:該路徑指向iOS和Android的沙盒路徑it

Application.streamingAssetsPath:streamingAsset文件夾路徑,在任何平臺均可以經過這個路徑讀取到文件夾裏的內容io

Application.temporaryCachePath:臨時數據文件路徑class

相關文章
相關標籤/搜索