본문 바로가기

Unity

[Unity] CSV 파싱하기

게임정보를 csv파일에 저장하고, 게임시작시 파싱하여 데이터를 관리하는 경우가 많다.

csv를 파싱하는방법을 알아보자

 

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("\\", "");
 
                value = value.Replace("<br>", "\n"); // 추가된 부분. 개행문자를 \n대신 <br>로 사용한다.
                value = value.Replace("<c>", ",");
 
                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;
    }
}

 

이 클래스는 스태틱이기 때문에 어디에서나 가져다 사용할수있다.

사용하는 방법

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
 
public class Test : MonoBehaviour
{
 
    public int _exp = 0;
 
    void Start()
    {
        List<Dictionary<string, object>> data = CSVReader.Read("knightIdle - playerChar");
 
        for (var i = 0; i < data.Count; i++)
        {
            Debug.Log("index " + (i).ToString() + " : " + data[i]["first"] + " " + data[i]["second"]);
        }

    }
}

csv파일 예시

참고로 csv는 2열부터 읽힌다.