낑깡의 게임 프로그래밍 도전기

240112 Parsing 본문

Unity C#

240112 Parsing

낑깡겜플밍 2024. 1. 12. 20:11
반응형

스트링은 매번 새객체를 찍어내기 때문에 사용시 주의

 

 

밑이 더 효율적

 

문자열은 불변성을 가지고 있어서 문자 하나만 바꾼게 아니라 새로 할당을 한것임 그래서 근본적인 문제는 해결되지 않고 있다.

그문제를 해결하기 위해 stringBuilder를 제공 해줬다.

똑같은 결과가 나오나 스트링을 배열로 할당을 하여 하나만 바꾼다.

그래서 자주 변경이 일어나는 것에 대해서는 스트링 빌더를 쓰라고 권장하고 있다.

 

CSV 형태 쉼표로 분리

 

한글로 바꿔주는 법
어디에 있든 이름만 이것이면 된다

 

using System.Collections;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;

public class Conversation
{
    private int spriteId;
    private string name;
    private string contents;

    public Conversation(int spriteId, string name, string contents)
    {
        this.spriteId = spriteId;
        this.name = name;
        this.contents = contents;
    }

    public void Show()
    {
        Debug.Log(name + " : " + contents);
    }
}

public class CSVParser
{
    public static List<string[]> Parse(string path)
    {
        List<string[]> valuesList = new List<string[]>();
        TextAsset loadData = Resources.Load<TextAsset>(path);
        string allText = loadData.text;
        string[] lines = allText.Split('\n');
        for (int i = 1; i < lines.Length; i++)
        {
            string[] values = lines[i].Split(',');
            if (lines[i] == "")
                continue;

            //values[0]//1  value[1]//유저A  value[2]//안녕
            valuesList.Add(values);
        }
        return valuesList;
    }
}


public class GameManager : MonoBehaviour
{
    string path = "conversationCSV";

    List<Conversation> conversationList;

    void Start()
    {
        conversationList = new List<Conversation>();
        List<string[]> valuesList = CSVParser.Parse(path);

        foreach (var values in valuesList)
            conversationList.Add(new Conversation(int.Parse(values[0]), values[1], values[2]));

    }

    int i = 0;
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            conversationList[i++].Show();
        }
    }
}
반응형

'Unity C#' 카테고리의 다른 글

팩토리 매서드 패턴, 추상 팩토리 패턴  (0) 2024.01.16
using UnityEngine.UI  (0) 2024.01.15
스크립터블 오브젝트  (0) 2024.01.08
유니티 리플렉션 어트리뷰트  (0) 2024.01.02
포톤  (0) 2023.12.14