Machineboy空

CSV파일 읽어오기, DataManager 본문

Game/Unity

CSV파일 읽어오기, DataManager

안녕도라 2023. 10. 18. 13:12
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;    
    }
}