Machineboy空
CSV파일 읽어오기, DataManager 본문
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//구조체 등을 다 때려넣는 클래스용으로 DataManager만들었다
[System.Serializable]
public class UserInfo
{
public string name;
public string phone;
public string email;
public int age;
public bool gender;
}
[System.Serializable]
public class ShopInfo
{
public string name;
public int price;
public int model;
}
public class DataManager : MonoBehaviour
{
public List<UserInfo> allUser;
public List<ShopInfo> allProduct;
// Start is called before the first frame update
void Start()
{
//allUser = CSV.instance.Parse("CSV_UNITY");
CSV.instance.Parse<UserInfo>("CSV_UNITY");
CSV.instance.Parse<ShopInfo>("CSV_SHOP");
}
// Update is called once per frame
void Update()
{
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Photon.Pun.Demo.Cockpit;
using System.ComponentModel;
public class CSV : MonoBehaviour
{
public static CSV instance;
private void Awake()
{
instance = this;
}
//reflection을 쓸 것
//where T : new() new라는 문법을 쓸 수 있다.
public List<T> Parse<T>(string fileName) where T : new()
{
//전체 T(UserInfo)를 가지고 있을 List
//List<UserInfo> list = new List<UserInfo>();
List<T> list = new List<T>();
//file을 읽어 오자. -> 읽어 와서 쉼표 기준으로 잘라낼 것이다.
string path = Application.streamingAssetsPath + "/" + fileName + ".csv";
string stringData = File.ReadAllText(path);
print(stringData);
//enter(\n or \r\n)를 기준으로 한 줄 한 줄 자르자
//우선 \n기준으로 자르고 그 다음\r 검사하자
string[] lines = stringData.Split("\n");
for (int i = 0; i < lines.Length; i++)
{
string[] temp = lines[i].Split("\r");
lines[i] = temp[0];
}
//,를 기준으로 변수를 나누자
string[] variables = lines[0].Split(",");
//,를 기준으로 값을 나누자.
for (int i = 1; i < lines.Length; i++)
{
string[] values = lines[i].Split(",");
#region
//잘라진 데이터를 가지고 UserInfo에 셋팅해서 리스트에 추가
//UserInfo info = new UserInfo();
//info.name = values[0];
//info.phone = values[1];
//info.email = values[2];
//info.age = int.Parse(values[3]);
//info.gender = bool.Parse(values[4]);
#endregion
//잘라진 데이터를 가지고 UserInfo에 세팅해서 리스트에 추가
T info = new T();
//어떤 자료형인지 알아서 분석해서 읽어오는 것을 reflection이라고 하나봄
for (int j = 0; j < variables.Length; j++)
{
//T에 있는 변수들의 정보를 가져오자.
//typeof 어떤 자료형인지 반환한다.
System.Reflection.FieldInfo fieldInfo = typeof(T).GetField(variables[j]);
//field의 타입에 따라 parse해주겠다. (int.parse 등)
TypeConverter typeConverter = TypeDescriptor.GetConverter(fieldInfo.FieldType);
//values를 typeConverter를 이용해서 변수에 세팅하자
if (values[j].Length >0)
{
fieldInfo.SetValue(info, typeConverter.ConvertFrom(values[j]));
}
}
// List에 채우자.
list.Add(info);
}
return list;
}
}
'Game > Unity' 카테고리의 다른 글
멀티플레이 구현: Photon Pun 유니티 기초 세팅 및 RPC 개념 (1) | 2024.09.10 |
---|---|
게임 엔진의 원리: 게임 오브젝트와 컴포넌트, 메시지와 브로드캐스팅 (0) | 2024.09.06 |
Unity 특수 폴더 Special folder names (0) | 2023.10.18 |
Script Life Cycle : Unity 이벤트 함수 실행 순서 (0) | 2023.09.20 |
LayerMask.GetMask / LayerMask.NameToLayer (0) | 2023.09.12 |