(Unity) 코드로 Directory 안의 File추적하기

고현서·2022년 12월 8일
1

특정 경로의 Directory 안의 File들을 추적할 수 있다!
참고로 File 추적은 Android에서는 안되는 것을 명심하라!
Directory 클래스 안에 GetFiles라는 메소드를 경로와 파일 형식을 함께 넣어 호출하면
file 경로들이 string 배열 형식으로 나오게 된다.

#if UNITY_STANDALONE
        string path = Application.dataPath + "/TextureImg";
#elif UNITY_IOS
        string path = Application.persistentDataPath + "/TextureImg";
#endif

        string[] fileEntries = Directory.GetFiles(path, "*.png");

        List<string> filenames = new List<string>();
        //썸네일 넣기
        foreach (string fileName in fileEntries)
        {
			//사용부
        }

사용 예시

다음 내용은 NFT Market Place에서 Emoji를 구매 후 앱에서 Updating을 했을 시 윈도우를 재설정 하는 코드이다!

참고로, Emoji를 Updating해서 다운받는 곳에서는 이름을 MarketEmoji[몇번째 순서]로 정한다.

이렇게 하여 뒤의 숫자로 Sort를 하면 모든 이모지를 순서대로 받을 수 있다.
Emoji는 총 12개만 있기 때문에 12개 단위로 나눠 카테고리 버튼을 첫번째 사진을 썸네일로 하고, 리스너에 등록하여 생성한다.

	/// <summary>
    /// 업데이트 후 윈도우 재설정
    /// </summary>
    public void Updating()
    {
        for(int i = emoji_Category_content.childCount - 1;i > 0; i--)
        {
            Destroy(emoji_Category_content.GetChild(i).gameObject);
        }
#if UNITY_STANDALONE
        string path = Application.dataPath + "/TextureImg";
#elif UNITY_IOS
        string path = Application.persistentDataPath + "/TextureImg";
#endif

        string[] fileEntries = Directory.GetFiles(path, "*.png");

        List<string> filenames = new List<string>();
        //썸네일 넣기
        foreach (string fileName in fileEntries)
        {
#if UNITY_STANDALONE
            filenames.Add(fileName.Split("/TextureImg\\")[1].Split('.')[0]);
#elif UNITY_IOS || UNITY_ANDROID
                    filenames.Add(fileName.Split("/TextureImg/")[1].Split('.')[0]);
#endif
        }
        filenames.Sort((x, y) => int.Parse(x.Split("Market_Emoji_")[1]).CompareTo(int.Parse(y.Split("Market_Emoji_")[1])));

        for (int i = 0; i < filenames.Count; i += 12)
        {
            int temp = i;
            GameObject prefab = Instantiate(emojiCatPrefab, emoji_Category_content);

            prefab.name = "EmojiCat_" + filenames[i];
            byte[] byteTexture = File.ReadAllBytes(path + "/" + filenames[i] + ".png");
            if (byteTexture.Length > 0)
            {
                Texture2D texture = new Texture2D(0, 0);
                texture.LoadImage(byteTexture);
                Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
                prefab.GetComponent<Image>().sprite = sprite;
            }
            prefab.GetComponent<Button>().onClick.AddListener(
                () => OnClickEmojiCategory(temp + 15));
        }
	}

주의!! 버튼에 리스너를 등록할때는 temp라는 임시 변수에 i를 넣어 클릭 이벤트 메소드 안에 temp를 넣어줘야 한다!
즉, 직접적으로 i를 넣지 말자!
왜냐하면, 순서가 뒤죽박죽 이거나 i의 가장 마지막 숫자로 등록되기 때문이다. 주의하자!

profile
New 현또의 코딩세상 / Unity 개발자

0개의 댓글