유니티

C#을 사용하여 Unity 폴더의 파일 목록 가져오기

민또배기 2023. 3. 11. 14:41
반응형

OS : Window 11

Version : 2021.3.16f1

 

유니티에서 폴더의 파일 목록을 가져오는 방법에 대해서 알아보겠습니다.

 

먼저 게임 오브젝트를 하나만들고 거기에 FileList라는 이름으로 컴포넌트를 추가합니다.

그리고 아래처럼 소스코드를 작성합니다.

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

public class fileList : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        DirectoryInfo di = new DirectoryInfo(Application.dataPath);

        foreach (FileInfo file in di.GetFiles())
        {
            Debug.Log("파일명 : " + file.Name);
        }
    }
}

 

추가 하셔야하는 건  using System.IO입니다. 

파일과 데이터 스트림에 대한 일기 및 쓰기를 허용하는 형식과 기본 파일 및 디렉터리 지원을 제공하는 형식이 포함되어 있는 네임스페이스

GetFiles를 이용하여 폴더내의 목록을 가져오면 됩니다.

그런데 저 파일 목록 중에 특정 파일만 가져오고 싶을 땐 다음과 같이 GetFiles에 "*.cs"를 넣어 줍니다. 

*.cs의 의미는 .cs의 확장자를 가진 파일을 가져온다는 의미 입니다. (앞에 있는 *는 모든 값을 의미합니다.)

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

public class fileList : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        System.IO.DirectoryInfo di = new DirectoryInfo(Application.dataPath);

        foreach (FileInfo file in di.GetFiles("*.cs"))
        {
            Debug.Log("파일명 : " + file.Name);
        }
    }
}

 

그러면 이전과 다르게 cs파일만 출력됩니다.

파일 전체경로를 출력하고 싶으시다면 file.Name이 아닌 file로 출력하시면 됩니다.

 

반응형