Lightweight CSV reader for Unity
September 13, 2014 19 Comments
Managing game data in Unity scene objects can get really painful especially when more than one people needs to edit the same thing. It’s usually better to have some data in CSV file where it can be controlled centrally.
When facing this problem I couldn’t find CSV reader for Unity that would have been exactly what I need. i.e. not be very buggy, huge or require new assembly dependencies.
So here is very simple CSV reader for Unity. It is bare bones but still robust enough parse quoted text and comma’s inside text. Reader assumes that csv files are in Resources
folder of your Unity project.
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; public class CSVReader { static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))"; static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r"; static char[] TRIM_CHARS = { '\"' }; public static List<Dictionary<string, object>> Read(string file) { var list = new List<Dictionary<string, object>>(); TextAsset data = Resources.Load (file) as TextAsset; var lines = Regex.Split (data.text, LINE_SPLIT_RE); 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; } }
Drop this in your Scripts folder as CSVReader.cs
and make folder Resources
under your Assets
folder. Put there any CSV files you want to use.
Example CSV file example.csv
in Resources
folder.
name,age,speed,description cat,2,4.5,"cat stalks, jumps and meows" dog,2,5.5,dog barks fish,1,1.1,fish swims
How to use
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Main : MonoBehaviour { void Awake() { List<Dictionary<string,object>> data = CSVReader.Read ("example"); for(var i=0; i < data.Count; i++) { print ("name " + data[i]["name"] + " " + "age " + data[i]["age"] + " " + "speed " + data[i]["speed"] + " " + "desc " + data[i]["description"]); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
See full example code in Github: https://github.com/tikonen/blog/tree/master/csvreader