본문 바로가기
개발/Unity

Unity) 특정 경로(Resource)의 하위 디렉토리 검색

by 테샤르 2023. 1. 3.

특정 경로(Resource)의 하위 디렉토리 검색

Resource의 특정 디렉토리를 기준으로 경로를 읽는 코드이다.

재귀처리로 LoadPathRecursive 에서 File 과 Directory 를 판단해서 다시 재귀 호출을 진행한다.


private static string[] FindFileExtension =
    {
        ".asset",
        ".png",
        ".jpg",
        ".prefab",
        ".json",
        ".cs",
    };
    
    public void Test()
    {

        PathInfo rootPath = new PathInfo();
        LoadPathsRecursive("", ref rootPath);
        PrintPath(rootPath);
    }

    private void PrintPath(PathInfo _info)
    {
        foreach (var file in _info.Files)
        {

            string view = $"{new string('\t', _info.depth +1 )}{file}";
            Debug.Log($"[Path] File : {view}");
        }

        foreach(var sub in _info.SubDiretory)
        {
            PrintPath(sub);
        }
    }

    
   
    public class PathInfo 
    {
        public string FullPath = string.Empty;
        public List<string> Files = new List<string>();
        public List<PathInfo> SubDiretory = new List<PathInfo>();
        public int depth = 0;
    }

    private  void LoadPathsRecursive(string path, ref PathInfo root)
    {
        var fullPath = Application.dataPath + "/Resources/" + path;
        Debug.Log($"Directory Root Path : {fullPath}");
        DirectoryInfo dirInfo = new DirectoryInfo(fullPath);
        root.FullPath = fullPath;

        //File
        foreach (var file in dirInfo.GetFiles())
        {
            string fileName = file.Name;
            if (fileName.Contains(".meta"))   //.meta 제외
                continue;

            int fulllLength = fileName.Length;
            int fileNameLength = Path.GetFileNameWithoutExtension(fileName).Length;
            string fileExtension = fileName.Substring(fileNameLength, fulllLength - fileNameLength);

            bool find = FindFileExtension.Any(x => x.Equals(fileExtension));
            if (find == false)      //확장자 안맞으면 제외
                continue;

            root.Files.Add(Path.GetFileNameWithoutExtension(fileName));
        }

        //Directories
        foreach (var dir in dirInfo.GetDirectories())
        {
            
            PathInfo subDirectory = new PathInfo();
            subDirectory.depth = (root.depth + 1);
            root.SubDiretory.Add(subDirectory);
            LoadPathsRecursive($"{path}/{dir.Name}", ref subDirectory);
        }

    }

특정 파일 확장자를 구분 처리도 되어있다.

간략하게 테스트해보면 다음과 같다.

반응형

 

 

Searching through all subfolders when using Resources.Load in Unity : [링크]

 

Searching through all subfolders when using Resources.Load in Unity

Is it possible to have Resources.Load(name, type) search for a fitting asset not just in the base Resources folder / a specified subfolder, but instead the full subfolder structure under Resources?

stackoverflow.com

 

★☆☆☆☆

 

 

 

 

 

반응형

댓글