본문 바로가기
Unity/Engine

유니티 특정 디렉토리 파일 불러오기

by 잡템 2022. 2. 14.

일반적으로 폴더에서 리소스를 불러올 때는 Resources폴더를 생성하고 Resources.Load를 많이 사용 하지만

 

본인이 따로 지정한 폴더에서 바로 불러오는 방법도 존재한다.

 

AssetDatabase.LoadAssetAtPath를 사용하면 되는데 

 

GameObject obj = (GameObject)AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Player.prefab", typeof(GameObject));

 

이런 식으로 사용하면 된다 다만 여러 파일을 불러와야 할 경우 Resources의 경우 Resources.LoadAll를 사용하면 해결이 되지만

 

AssetDatabase의 경우 LoadAllAssetPath함수가 존재하지만 이 메서드의 용도는 Fbx 파일과 같이 파일 내에 여러 에셋이 포함된 파일을 불러올 때 사용하는 함수고 Resources.LoadAll과 같은 기능을 하지 않는다.

 

그래서 Resources를 사용하지 않고 여러 파일을 불러오려면 System.IO.Directory.GetFiles을 사용해 특정 폴더 내의 파일명을 모두 불러온 뒤 LoadAssetAtPath를 사용해 삽입하면 여러 파일을 특정 폴더에서 불러서  등록할 수 있다

 

(예시)

        <*.prefab은 .prefab으로 끝나는 파일명을 저장하기 위한 검색 패턴이다>

        string[] paths = System.IO.Directory.GetFiles("Assets/Prefabs/Player","*.prefab");

        GameObject[] PlayerObjs = new GameObject[paths.Length];


        for(int i= 0; i< paths.Length; ++i)
        {
            PlayerObjs[i] = (GameObject)AssetDatabase.LoadAssetAtPath(paths[i], typeof(GameObject));
        }

 

Reference

https://tenlie10.tistory.com/157

 

[Unity | 유니티] 특정 디렉토리에서 프리팹 또는 파일 로드하기

경로에 있는 첫번재 오브젝트를 찾아 반환한다. 경로는 대소문자를 구분함에 유의해야 한다. 오브젝트를 찾지 못하면 Null을 반환한다. 1 2 3 4 5 6 7 8 9 10 11 using UnityEngine; using UnityEditor; public..

tenlie10.tistory.com

https://stackoverflow.com/questions/41589158/loadallassetsatpath-is-returning-an-empty-array-in-unity

 

LoadAllAssetsAtPath is returning an empty array in Unity

I need to have access to all assets in a specific file in my code. So I'm using the following line of code: Object[] objects = AssetDatabase.LoadAllAssetsAtPath("Assets/GameData/Games/01.games"); ...

stackoverflow.com