파일 저장 경로 불러오는 코드 작성
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);
}
}
}
}
'게임엔진 > 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 |