본문 바로가기

Engine/Unity 그때그때 끄적끄적

[Unity] CSV파일 읽고 사용하기

 

 예전에 게임잼에참가했었을때 다른 프로그래머분이 txt파일이나 json,csv 파일들을 따로만들어 기획자분이 관리하기 편하게 작업을해줬던 기억이있다

나도 언젠가는 저런걸 할 수 있겠지하며 지나갔었는데

이번포스팅에는 CSV 파일을 이용하여 파싱하여 유니티에 적용하는 방법에 대해 알아보려고한다

 

 CSV란 comma-separated values의 약자로 몇 가지 필드를 쉼표(,)로 구분한 텍스트 데이터 및 텍스트 파일 이라고한다.

간단하게 정보와 쉼표로 이루어진 텍스트 파일이라고 이해하면 편하다

 

CSV을 만드는 방법부터 알아보자

우선 Excel 파일부터 만들자

첫번째열은 Header라고하며 하위항목들을 설명 해주는 항목이다 나중에 인덱스 접근에 사용하게된다

이렇게 Excel 파일은 만든다음 다른이름으로 저장을 눌러 CSV파일로 저장을 하면 된다

CSV파일로 저장
CSV파일 형태

위과정을 거치면 아래와같은 CSV 파일을 얻을 수 있다 이렇게 얻은 파일을 유니티 Resources 폴더 안에 넣어주면 된다

https://docs.unity3d.com/kr/530/ScriptReference/Resources.html

 

Unity - 스크립팅 API: Resources

에디터에서, Resources.FindObjectsOfTypeAll기능은 에셋과 씬 오브젝트를 찾는 데 사용할 수 있습니다. Assets폴더 내 "Resources"이름을 가진 폴더안의 모든 에셋은 Resources.Load 함수를 통해서 접근할 수 있습

docs.unity3d.com

곧나올 CSV Reader클래스에서 Load함수를 사용하여 Resources 폴터에있는 해당 CSV파일을 읽어오기때문에 반드시 Resources 폴더를만들고(철자틀리면안된다 조심할것) 그안에 해당 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("\\", "");
                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;
    }
}

 

https://bravenewmethod.com/2014/09/13/lightweight-csv-reader-for-unity/#comment-7111

 

Lightweight CSV reader for Unity

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 …

bravenewmethod.com

CSV Reader 클래스의 출처이다 어디를가도 이것을 사용하고있는거같다 코드에 대한 분석은 다음기회에 하는걸로하고 우선 해당 코드를 복붙하여 사용법부터 익히도록하겠다

프로젝트에 스크립트를 만들어 해당 코드를 복붙하고

위코드와 같이 CSVReder.Read(파일이름)

data[행][원하는 header이름]으로 접근하여 사용하면된다

 

'Engine > Unity 그때그때 끄적끄적' 카테고리의 다른 글

[Unity] 애니메이션  (0) 2021.07.30
[Unity] 네비게이션  (0) 2021.07.23
[Unity] 화면 전환  (0) 2021.07.14
[Unity] 싱글톤 패턴  (0) 2021.07.13
[Unity] Sprite Atlas 활용하기  (0) 2021.07.08