본문 바로가기

정리 카테고리/개인복습&정리

[수정*1회]Unity 에서 CSV확장자 불러와 결과 보기

이내용에 대한 출처는 아래와 같습니다.

http://blog.naver.com/PostView.nhn?blogId=bbulle&logNo=220158917236&parentCategoryNo=&categoryNo=36&viewDate=&isShowPopularPosts=false&from=postView


왼쪽의 excel 내용을 .csv 확장자로 저장후  오른쪽과 같이 나오게 되는 소스와 결과 화면 입니다.




위의 내용의 csv 파일은 아래 파일로 올렸습니다.

testuser.csv


csv의 파일의 경로는 Assets 폴더안에 Resources폴더 안에 넣습니다.




List<Dictionary<stringobject>> data = CSVReader.Read("testuser");

부분에서 "" 안에 csv파일명이 들어갑니다.



                         

+확인된 내용은 다음과 같으며 경로와 기타 소스 이해는 지금부터 진행할 예정입니다.


Resources.Load(file) -> resources 폴더에서 파일을 읽어온다.

unity Engin에서 제공하는 API다(https://docs.unity3d.com/ScriptReference/Resources.Load.html)


파일에서 불러온것은 Text Assets(=임포트한 텍스트 파일의 포맷)통해 받아 (->unity API에 나와있다)


Regex.Split( )을 통해 다시 정리된다. (SPLIT_RE를 조금더 정리하고 나머지도 메모하려 한다.)




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
 
public class CSVReader {
 
    public static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
    public static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
    public static char[] TRIM_CHARS = { '\"' };
 
    public static List<Dictionary<stringobject>> Read(string file)
    {
        var list = new List<Dictionary<stringobject>>();
        TextAsset data = Resources.Load(file) as TextAsset;
 
        var lines = Regex.Split(data.text, LINE_SPLIT_RE);
 
        if (lines.Length <= 1return 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<stringobject>();
            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;
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Test : MonoBehaviour {
 
    public string _exp;
    void Start () {
        List<Dictionary<stringobject>> data = CSVReader.Read("testuser");
 
        for (var i = 0; i < data.Count; i++)
        {
            Debug.Log("index " + (i).ToString() + " : " + data[i]["id"+ " " + data[i]["name"+ " " + data[i]["default_damage"]);
        }
 
        _exp = data[1]["name"].ToString();
        Debug.Log(_exp);
        Debug.Log(data);
    }
 
}
cs