Unity에서 C#의 메모장(.txt)를 읽기를 위한 코드 예제

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System;
using System.IO; // 파일입출력을 하기위한 네임스페이스

public struct SummonEnemy
{
    public string Enemy_name;
    public float Enemy_Summon_Time;
    public Vector2 Enemy_start_Pos;

}

public class FileReader : MonoBehaviour
{
    List<SummonEnemy> summonEnemies = new List<SummonEnemy>();

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            string filePath = "Assets/FileReadText/Example.txt";
            ReadTxt(filePath);
        }
    }

    string ReadTxt(string filePath)
    {
        FileInfo fileInfo = new FileInfo(filePath);
        string value = "";

        string[] Enemy = new string[4];

        

        if (fileInfo.Exists)
        {
            StreamReader reader = new StreamReader(filePath);
            while((value = reader.ReadLine()) != null)
            {
                SummonEnemy summonEnemy = new SummonEnemy();
                
                Enemy = value.Split(',');

                summonEnemy.Enemy_name = Enemy[0];
                summonEnemy.Enemy_Summon_Time = float.Parse(Enemy[1]);
                summonEnemy.Enemy_start_Pos = new Vector2(float.Parse(Enemy[2]), float.Parse(Enemy[3]));


                summonEnemies.Add(summonEnemy);
            }

            foreach(SummonEnemy readenemy in summonEnemies)
            {
                Debug.Log(readenemy.Enemy_name + readenemy.Enemy_Summon_Time + readenemy.Enemy_start_Pos);
            }

            reader.Close();
        }

        else
            value = "파일이 없습니다.";

        return value;
    }
}

+ Recent posts