Skip to content

Instantly share code, notes, and snippets.

@SiarheiPilat
Last active February 18, 2023 14:50
Show Gist options
  • Save SiarheiPilat/de4688651f106e7993a7e2fdb743cac4 to your computer and use it in GitHub Desktop.
Save SiarheiPilat/de4688651f106e7993a7e2fdb743cac4 to your computer and use it in GitHub Desktop.
A lightweight CSV reader for Unity.
using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;
// original: https://github.com/tikonen/blog/blob/master/csvreader/CSVReader.cs
// IMPORTANT: CSV FILE MUST BE IN THE RESOURCES FOLDER
// USAGE EXAMPLE FOR A 3 COLUMN CSV FILE:
//
// [ContextMenu("test csv data")]
// public void TestCsvData()
// {
// List<Dictionary<string, object>> data = CsvReader.ReadFromFile("shredder_objects");
// for (int i = 0; i < data.Count; i++)
// {
// Debug.Log(data[i]["name"] + ": " + data[i]["price"] + ", " + data[i]["reward"]);
// }
// }
public class CsvReader
{
static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
static char[] TRIM_CHARS = { '\"' };
/// <summary>
/// Reads a CSV file located in Resources folder.
/// </summary>
public static List<Dictionary<string, object>> ReadFromFile(string fileName)
{
TextAsset data = Resources.Load(fileName) as TextAsset;
var lines = Regex.Split(data.text, LINE_SPLIT_RE);
return ProcessLines(lines);
}
public static List<Dictionary<string, object>> ReadFromString(string str)
{
var lines = Regex.Split(str, LINE_SPLIT_RE);
return ProcessLines(lines);
}
static List<Dictionary<string, object>> ProcessLines(string[] lines)
{
var list = new List<Dictionary<string, object>>();
if (lines.Length <= 1) return list;
var header = Regex.Split(lines[0], SPLIT_RE);
for (var i = 1; i < lines.Length; i++)
{
var values = Regex.Split(lines[i], SPLIT_RE);
if (values.Length == 0 || values[0] == "") continue;
var entry = new Dictionary<string, object>();
for (var j = 0; j < header.Length && j < values.Length; j++)
{
string value = values[j];
value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
object finalvalue = value;
int n;
float f;
if (int.TryParse(value, out n))
{
finalvalue = n;
}
else if (float.TryParse(value, out f))
{
finalvalue = f;
}
entry[header[j]] = finalvalue;
}
list.Add(entry);
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment