ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1068) N
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (181) N
      • Unreal (69)
      • Unity (101) N
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 백준
  • 티스토리챌린지
  • Unity
  • 알고리즘
  • 클래스
  • 오블완
  • 포인터
  • 배열
  • 그래픽스
  • 파이썬
  • 함수
  • c#
  • 프로그래머스
  • 언리얼
  • C++
  • 유니티
  • string
  • 문자열
  • SQL
  • C

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

게임엔진/Unity

[Unity] CSV 파일 저장, 불러오기 Read, Write 간단 사용법

2023. 9. 18. 16:14

파일 저장 경로 불러오는 코드 작성

using System.IO;
using UnityEngine;

public static class SystemPath
{
    public static string GetPath(string fileName)
    {
        string path = GetPath();
        return Path.Combine(GetPath(), fileName);
    }

    public static string GetPath()
    {
        string path = null;
        switch (Application.platform)
        {
            case RuntimePlatform.Android:
                path = Application.persistentDataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(Application.persistentDataPath, "Resources/");
            case RuntimePlatform.IPhonePlayer:
            case RuntimePlatform.OSXEditor:
            case RuntimePlatform.OSXPlayer:
                path = Application.persistentDataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(path, "Assets", "Resources/");       
            case RuntimePlatform.WindowsEditor:
                path = Application.dataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(path, "Assets", "Resources/");
            default:
                path = Application.dataPath;
                path = path.Substring(0, path.LastIndexOf('/'));
                return Path.Combine(path, "Resources/");
        }
    }
}

 

 

CSV Reader 작성

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;

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>>();
        string[] lines;

        if (File.Exists(SystemPath.GetPath() + file + ".csv"))
        {
            string source;
            StreamReader sr = new StreamReader(SavePath.GetPath() + file + ".csv");
            source = sr.ReadToEnd();
            sr.Close();

            lines = Regex.Split(source, LINE_SPLIT_RE);

            Debug.Log("Load " + file + ".csv");
        }
        else
        {
            return null;
        }

        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");
                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;
    }
}

 

 

CSV 파일 저장하기

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CSVManager : MonoBehaviour
{
    public string fileName = "Setting.csv";

    public InputField nameText;
    public InputField countryText;
    public InputField yearText;
    public InputField heightText;
    
    List<string[]> data = new List<string[]>();
    string[] tempData;
    
    void Awake()
    {
    	data.Clear();
        
        tempData = new string[4];
        tempData[0] = "Name";
        tempData[1] = "Country";
        tempData[2] = "Year";
        tempData[3] = "Height";
        data.Add(tempData);
	}
    
    public void SaveCSVFile()
    {
    	tempData = new string[4];
        tempData[0] = nameText.text;
        tempData[1] = countryText.text;
        tempData[2] = yearText.text;
        tempData[3] = heightText.text;
        data.Add(tempData);
        
        string[][] output = new string[data.Count][];

        for (int i = 0; i < output.Length; i++)
        {
            output[i] = data[i];
        }

        int length = output.GetLength(0);
        string delimiter = ",";

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < length; i++)
        {
            sb.AppendLine(string.Join(delimiter, output[i]));
        }

        string filepath = SystemPath.GetPath();

        if (!Directory.Exists(filepath))
        {
            Directory.CreateDirectory(filepath);
        }

        StreamWriter outStream = System.IO.File.CreateText(filepath + fileName);
        outStream.Write(sb);
        outStream.Close();
    }
}

 

 

CSV 파일 불러오기

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class CSVManager : MonoBehaviour
{
    public string fileName = "Setting";

    public InputField nameText;
    public InputField countryText;
    public InputField yearText;
    public InputField heightText;
    
    List<Dictionary<string, object>> dicList = new List<Dictionary<string, object>>();
    
    void Awake()
    {

    }
    
    public void LoadCSVFile()
    {
    	dicList.Clear();

        dicList = CSVReader.Read(fileName);

        nameText.text = dicList[0]["Name"].ToString();
        countryText.text = dicList[0]["Country"].ToString();
        yearText.text = dicList[0]["Year"].ToString();
        heightText.text = dicList[0]["Height"].ToString();
        
        // 개인적으론 위 방법보단 아래를 사용할듯
        foreach (var data in dicList)
        {
        	try
            {
            	data.TryGetValue("Name", out object nameRef);
                nameText.text = nameRef as string;
                
                // 위와 같이 나머지것들도 동일하게 처리.
            }
            catch (System.Exception ex)
            {
            	Debug.LogError(ex.Message);
            }
        }
    }
}

 

유니티 C# CSV 파일 저장, 불러오기 Read, Write 간단 사용법 (tistory.com)

저작자표시 (새창열림)

'게임엔진 > Unity' 카테고리의 다른 글

[Unity] 플랫폼별 컴파일 (전처리기)  (0) 2023.09.22
[Unity] 레이어 소팅레이어 태그 설정  (0) 2023.09.19
[Unity] Visual Studio에서 디버깅 연결이 되지 않는 경우  (0) 2023.09.18
[Unity] Resources.LoadAll로 리소스 파일 전체 불러오기  (0) 2023.09.15
[Unity] UniTask VS Task (UniTask 개념 포함)  (0) 2023.09.13
    '게임엔진/Unity' 카테고리의 다른 글
    • [Unity] 플랫폼별 컴파일 (전처리기)
    • [Unity] 레이어 소팅레이어 태그 설정
    • [Unity] Visual Studio에서 디버깅 연결이 되지 않는 경우
    • [Unity] Resources.LoadAll로 리소스 파일 전체 불러오기
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바