상세 컨텐츠

본문 제목

[Unity] 유니티 로컬 파일 읽어들이기(이미지, 파일 등등)

게임엔진관련/유니티 엔진

by AlrepondTech 2020. 1. 14. 00:26

본문

반응형

 

 

 

 

 

 

=======================

=======================

=======================

 

 

 

 

 

 

 

 

출처: http://blog.kpaper.com/2017/02/unity3d.html

Unity3D 외부 리소스 가져오기

 

유니티로 빌드하면 에셋이 묶여서 엑세스가 불가하게 된다.
대량의 에셋을 추가하려면 에셋 번들을 이용하면 되는데,
이런 경우 말고 직접 리소스를 추가하고 싶은 경우가 있다.

최근 프로젝트에서 필요해서 하는김에 간단히 정리해봤다.
처음 하는 사람들에게 도움이 되길 -_-*

# Resource.Load 사용하기

private void ResourceLoadSample(){ 
  Texture2D texture = new Texture2D(0, 0);  
  string PATH = "Texture/image.jpg";    // 이미지 파일 패스를 써준다.  
  //중요한 것은 유니티 프로젝트 Assets/Resource/ 폴더 이후의 경로를 써주는 것이다.

  // 이 폴더는 맘대로 바꿀 수가 없다. 
  texture = Resources.Load(PATH,typeof(Texture2D)) as Texture2D;  // 이미지 로드 
  targetObject.mainTexture = texture;  // 타겟 오브젝트에 메인 텍스쳐를 넣어준다. 

} 

 

 

# System.File.IO로 직접 가져오기
Resource 폴더가 아니라 다른 폴더 특히 StreamingAssets에서 가져오려면
Resource.Load 함수를 쓰지 말고 직접 System.File.IO 로 가져와야 한다.
byte[] 로 가져온 다음에 Texture2D.LoadImage()를 사용하여 텍스쳐2D로 읽어오면 된다.

private void SystemIOFileLoad(){
byte[] byteTexture = System.IO.File.ReadAllBytes(Path);
if (byteTexture.Length > 0) {
          texture = new Texture2D(0, 0);
          texture.LoadImage(byteTexture);
}
}

 


# 원하는 경로/파일에 엑세스 하기
# StreamingAssets 폴더의 하위 폴더/파일에 접근해본다.

Path = System.IO.Path.Combine(Application.streamingAssetsPath, path); // path = 하위폴더 "하위폴더1/하위폴더2/file.png";

 

 

 

 

=======================

=======================

=======================

 

 

 

 

 

반응형

 

 

728x90

 

 

 

 

출처: https://knightk.tistory.com/37

 

간혹 빌드가 끝나고나서 특정 이미지를 교체해야 하거나 영상을 바꿔야 되면 해당 비디오 파일 또는 이미지 파일을 교체 후 새롭게 빌드를 시켜야 하는 번거러운 작업을 해야할 경우가 생긴다.

교체해야할 상황이 빈번하다고 판단되는 프로젝트일 경우 특정 폴더에 교체 할 소스 파일을 넣어두고 해당 소스파일만 바꾸면 새로 빌드할 필요가 없게 미리 처리해 두면 될 것이다. 

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

public class FileItemHandler : MonoBehaviour {

    public string ParentFolderName;
    public string TargetFolderName;
    public List FilePathList;
    public List CoverPathList;
    public List CoverSpriteList;
    string filepath;
    

    void Awake () { GetPathList (); }

    void GetPathList () {
        string _path = "";

        //타켓 폴더 패스 설정
        if (Application.platform == RuntimePlatform.Android) {
            //android일 경우 //
            _path = AndroidRootPath () + "Download/FH/" + ParentFolderName + "/" + TargetFolderName;
        } else {
            //unity일 경우 //
            _path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal) + "/Desktop/FH/" + ParentFolderName + "/" + TargetFolderName;
        }

        DirectoryInfo Folder = new DirectoryInfo (_path);

        //각 비디오의 패스(URL) 리스트 만들기
        foreach (var file in Folder.GetFiles ()) {  

           
             if (file.Extension != ".meta" && file.Extension != ".DS_Store") { //비디오 이외의 확장자를 가진 파일 제외시키기    
                filepath = _path + "/" + file.Name;
                if (!filepath.Contains ("._")) { //파일명 에러 수정해주기
                    // filepath = filepath.Replace ("._", "");
                    if (filepath.Contains (".mp4")) //비디오 파일 add 리스트
                        FilePathList.Add (filepath);
                    else if (filepath.Contains (".jpg")) { //커버이미지 파일 add 리스트
                        CoverPathList.Add (filepath);
             

                       Texture2D tex = null;
                        byte[] filedata;
                        if (File.Exists (filepath)) {
                            filedata = File.ReadAllBytes (filepath);
                            tex = new Texture2D (2, 2);
                            tex.LoadImage (filedata);
                            // Sprite sp = SpriteFromTexture2D (tex);
                            CoverSpriteList.Add (tex);
                        }
                    }
                }
            }
        }
        Debug.Log(ParentFolderName + "/" + TargetFolderName + ", FileCount : " + FilePathList.Count+ ",, SpriteCount : " + CoverSpriteList.Count);
    }

    string AndroidRootPath () {
        string[] temp = (Application.persistentDataPath.Replace ("Android", "")).Split (new string[] { "//" }, System.StringSplitOptions.None);
        return (temp[0] + "/");
    }

    Sprite SpriteFromTexture2D (Texture2D texture) {
        return Sprite.Create (texture, new Rect (0.0f, 0.0f, texture.width, texture.height), new Vector2 (0.5f, 0.5f), 100.0f);
    }


}




 

 

 

=======================

=======================

=======================

 

 

 

반응형


관련글 더보기

댓글 영역