IdleGirl/Assets/2_Codes/CSVReader.cs

91 lines
3.3 KiB
C#

using UnityEngine;
using System.Collections.Generic;
using System.IO;
public static class CSVReader
{
public static Dictionary<int, Dictionary<string, object>> Read(string filePath)
{
Dictionary<int, Dictionary<string, object>> dict = new Dictionary<int, Dictionary<string, object>>();
TextAsset textData = Resources.Load<TextAsset>("CSV/" + filePath);
using (StringReader reader = new StringReader(textData.text))
{
string[] headers = reader.ReadLine().Split(',');
reader.ReadLine(); // Skip the second line with column descriptions
int rowIndex = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
string[] values = line.Split(',');
Dictionary<string, object> entry = new Dictionary<string, object>();
for (int i = 0; i < headers.Length; i++)
{
string key = headers[i];
string prefix = key.Substring(0, 2);
if (values.Length > i)
{
string value = values[i];
switch (prefix)
{
case "n_":
entry.Add(key, int.Parse(value));
break;
case "l_":
entry.Add(key, System.Numerics.BigInteger.Parse(value));
break;
case "f_":
entry.Add(key, float.Parse(value));
break;
case "s_":
case "e_":
entry.Add(key, value);
break;
case "b_":
entry.Add(key, value == "1" ? true : false);
break;
default:
entry.Add(key, value);
break;
}
}
else
{
switch (prefix)
{
case "n_":
entry.Add(key, 0);
break;
case "l_":
entry.Add(key, System.Numerics.BigInteger.Zero);
break;
case "f_":
entry.Add(key, 0.0f);
break;
case "s_":
case "e_":
entry.Add(key, "");
break;
case "b_":
entry.Add(key, false);
break;
default:
entry.Add(key, "");
break;
}
}
}
dict.Add(rowIndex, entry);
rowIndex++;
}
}
return dict;
}
}