프로젝트 내 에셋들의 파일주소는 다음과 같이 얻어야 한다 안드로이드에서는 못 쓴다.
앞부분에 Assets/가 있으면 중첩될수도 있으니 그럴땐 겹치는 부분을 지우고 합쳐야한다
return $"{Application.dataPath}/{파일명}.txt";
세이브 데이터 경로
string filePath= $"{Application.persistentDataPath}/{fileName}.csv";
바이트배열 모두 읽기
byte[] datas=System.IO.File.ReadAllBytes(파일주소);
바이트배열 모두 쓰기
System.IO.File.WriteAllBytes(파일주소, 바이트배열);
문자열(텍스트) 모두 쓰기
string fileName = "save";
string filePath = $"{fileName}.txt";
string data = sb.ToString();
System.IO.File.WriteAllText(filePath, data);
문자열(텍스트) 모두 읽기
string filePath = $"{fileName}.txt";
string data = null;
if (System.IO.File.Exists(filePath))
{
data = System.IO.File.ReadAllText(filePath);
}
아래와 동일함
public static bool SaveAllTextType2(string fileName, string data)
{
try
{
System.IO.File.WriteAllBytes(filePath, System.Text.Encoding.Default.GetBytes(data));
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
throw;
}
}
public static bool SaveAllText(string fileName, string value)
{
try
{
FileStream fs = new FileStream(fileName, FileMode.Create);
StreamWriter st = new StreamWriter(fs, Encoding.UTF8);
st.Write(value);
st.Close();
fs.Close();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
throw;
}
}
public static string ReadAllText(string fileName)
{
try
{
FileStream fs = new FileStream(fileName, FileMode.Open);
StreamReader st = new StreamReader(fs, Encoding.UTF8);
string data = st.ReadToEnd();
st.Close();
fs.Close();
return data;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
throw;
}
}
JSON 저장 읽기
이중클래스 저장시에는 내부에 들어가는 클래스에
[System.Serializable]가 붙어야 한다
HashTable, Dictionary는 저장불가
v1~v2
더보기
public static string filePath
{
get
{
return $"{Application.persistentDataPath}/{nameof(SaveClass)}.json";
}
}
//쓰기
System.IO.File.WriteAllText(filePath, JsonUtility.ToJson(saveClass));
//읽기
if(System.IO.File.Exists(filePath))
{
saveClass= JsonUtility.FromJson<SaveClass>(System.IO.File.ReadAllText(filePath));
}
else
{
saveClass = new SaveClass();
}
V2
public class SaveClass
{
public static string filePath
{
get
{
return $"{Application.persistentDataPath}/{GetType().Name}.json";
}
}
public void Save()
{
System.IO.File.WriteAllText(filePath, JsonUtility.ToJson(this));
}
public static SaveClass Load()
{
if (System.IO.File.Exists(filePath))
{
return JsonUtility.FromJson<SaveClass>(System.IO.File.ReadAllText(filePath));
}
else
{
return new SaveClass();
}
}
}
public class TargetClass : MonoBehaviour
{
public static SaveClass saveClass;
// Start is called before the first frame update
void Start()
{
saveClass = SaveClass.Load();
}
public void SetData()
{
saveClass.Save();
}
// Update is called once per frame
void Update()
{
}
}
V3
public class SaveClass
{
public double[] Datas { get; set; }
string FilePath
{
get
{
return $"{Application.StartupPath}/{GetType().Name}.json";
}
}
public void Save()
{
System.IO.File.WriteAllText(FilePath, JsonSerializer.Serialize(this));
}
public static SaveClass Load()
{
return new SaveClass().LoadThis();
}
SaveClass LoadThis()
{
if (System.IO.File.Exists(FilePath))
{
return JsonSerializer.Deserialize<SaveClass>(System.IO.File.ReadAllText(FilePath));
}
else
{
Datas = new double[15];
return this;
}
}
}
public class TargetClass : MonoBehaviour
{
public static SaveClass saveClass;
// Start is called before the first frame update
void Start()
{
saveClass = SaveClass.Load();
}
public void SetData()
{
saveClass.Save();
}
// Update is called once per frame
void Update()
{
}
}
폴더가 없으면 만들기
if (System.IO.Directory.Exists(folderPath) == false)
{
System.IO.Directory.CreateDirectory(folderPath);
}
해당 파일의 폴더경로(폴더명)를 반환
folderPath = filePath.Substring(0, Mathf.Max(filePath.LastIndexOf("/"), filePath.LastIndexOf(@"\")));
V2
var folderPath = System.IO.Path.GetDirectoryName(filePath);
파일 삭제하기
public static bool Delete(string filePath)
{
if (!System.IO.File.Exists(filePath))
{
return false;
}
System.IO.File.Delete(filePath);
return true;
}
윈도우에서 폴더 열기(실행)
System.Diagnostics.Process.Start(folderPath);
파일 복사
경로는 확장자도 포함 되어야 하고 C:/과 같이 드라이브 명으로 시작하는 경로여야함
System.IO.File.Copy(불러올파일경로, 저장될파일경로);
파일이름 반환 구버전
더보기
public static string GetFileName(string filePath)
{
int filePath_LastIndexOf = filePath.LastIndexOf("/");
if (filePath_LastIndexOf > 0)
{
filePath = filePath.Substring(filePath_LastIndexOf + "/".Length, filePath.Length - (filePath_LastIndexOf + "/".Length));
}
return filePath;
}
확장자 붙은 파일이름 반환 (유니티, 윈도우 겸용)
string fileName = System.IO.Path.GetFileName("경로");
확장자 없는 파일이름 반환 (유니티, 윈도우 겸용)
string fileName = System.IO.Path.GetFileNameWithoutExtension("경로");
파일이름들 반환
해당 파일 주소 바로 아래의 파일들을 가져온다. 아래아래같은경우엔 안됨
c:/부터 시작하는 파일경로를 쭉 불러와서 확장자까지 반환한다.
이상하게 파일명 앞에는 /이 아니고 \가 붙음. 쓰는덴 지장없다
//리스트 반환
List<string> filePaths = new List<string>(System.IO.Directory.GetFiles(폴더주소));
//배열 반환
string[] filePaths = System.IO.Directory.GetFiles(폴더주소);
//교정후 반환
List<string> filePaths = new List<string>(System.IO.Directory.GetFiles(folderPath)).ConvertAll(x=> x.Replace(@"\","/"));
확장자 반환
.콤마 포함
System.IO.Path.GetExtension(path)==".asmdef"
파일 정보 (파일시간, 파일용량 등)
var info = new System.IO.FileInfo(filePath);
string md5 = $"{GetMD5(System.IO.File.ReadAllBytes(filePath))}";
string version = $"{info.LastWriteTimeUtc.Ticks / 10000000 }";
string fileSize = $"{info.Length}";
zip압축/해제
쓰려면 Plugins/Windows/System.IO.Compression.FileSystem.dll이 필요하다
//압축
System.IO.Compression.ZipFile.CreateFromDirectory(압축할 폴더주소, 저장될 zip 파일 주소+".zip");
//압축해제
System.IO.Compression.ZipFile.ExtractToDirectory(zip 파일 주소+".zip", 압축해제할 폴더주소);
unityzip
ZipUtil.Zip(저장될파일주소, System.IO.Directory.GetFiles(압축할폴더주소));
//위아래 동일함
System.IO.Compression.ZipFile.CreateFromDirectory(압축할폴더주소, 저장될파일주소);
파일탐색기 열어서 파일 위치 반환
(파일 다이얼로그,윈폼기반)
유니티에서 쓰려면 System.Windows.Forms.dll이 있어야 하는데 생각보다 복잡하므로
스탠드얼론 파일 브라우저를 쓰자(하단 참조)
public static string FileSearch()
{
System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
//openFile.DefaultExt = "png";
//openFile.Filter = "(*.txt)|*.txt";
openFile.Filter = "All files(*.*)|*.*";
openFile.ShowDialog();
if (openFile.FileName.Length > 0)//파일이선택될경우
{
return openFile.FileName;
}
return "";
}
유니티기반 다이얼로그
에디터 전용
c:/로 시작하는 경로를 반환함
string path = EditorUtility.OpenFilePanel("Overwrite with png", "", "png");
string path = EditorUtility.OpenFilePanel("Overwrite with img", "", "png;*.jpg");
유니티 스탠드얼론 파일 브라우저 (기본적으로 위와 같음) (2019.4.1.f1지원, 2019.4.31f1 미지원)
https://github.com/gkngkc/UnityStandaloneFileBrowser
string[] paths=SFB.StandaloneFileBrowser.OpenFilePanel("Open File", "", "txt", false);
스탠드얼론으로 폴더경로 받을때
{
var paths = SFB.StandaloneFileBrowser.OpenFilePanel("Open File", "", "txt", false);
{
if (paths.Length > 0)
{
var filePath = paths[0];
var folderPath = System.IO.Path.GetDirectoryName(filePath);
return folderPath;
}
}
return null;
}
object to path
오브젝트의 path를 반환함
Asset/로 시작하는 경로를 반환함
string path = AssetDatabase.GetAssetPath(오브젝트);
폴더 삭제
if (System.IO.Directory.Exists(folderPath))
{
System.IO.Directory.Delete(folderPath, true);
}
에셋폴더오브젝트의 하위폴더 이름들을 반환
#if UNITY_EDITOR
public static string[] GetFolderNames(Object folder)
{
string folderPath = UnityEditor.AssetDatabase.GetAssetPath(folder);
string[] folderPaths = UnityEditor.AssetDatabase.GetSubFolders(folderPath);
string[] folderNames = System.Array.ConvertAll(folderPaths, x => System.IO.Path.GetFileName(x));
return folderNames;
}
public static string[] GetFolderNames(string folderPath)
{
string[] folderPaths = UnityEditor.AssetDatabase.GetSubFolders(folderPath);
string[] folderNames = System.Array.ConvertAll(folderPaths, x => System.IO.Path.GetFileName(x));
return folderNames;
}
#endif
특정 에셋폴더가 있는지 검사
바로 위 스크립트랑 같이씀
var assetsFolderNames = GetFolderNames("Assets");
if (assetsFolderNames.Contains("DynamicBone"))
{
Debug.Log("다이나믹본 폴더가 존재함");
}
if (assetsFolderNames.Contains("VRCSDK"))
{
Debug.Log("VRCSDK 폴더가 존재함");
}
에셋들을 전부 리로드
AssetDatabase.CreateAsset에는 필요없음
AssetDatabase.Refresh();
특정파일만 리프레시함
AssetDatabase.ImportAsset (파일경로);
폴더오브젝트에서 마테리얼, 텍스처들을 반환
static Material[] GetFolderToMaterials(Object folder)
{
var folderPath = AssetDatabase.GetAssetPath(folder);
var guids = AssetDatabase.FindAssets($"t:{typeof(Material).Name}", new string[] { folderPath });
var assets = new Material[guids.Length];
for (int i = 0; i < assets.Length; i++)
{
assets[i] = AssetDatabase.LoadAssetAtPath<Material>(AssetDatabase.GUIDToAssetPath(guids[i]));
}
return assets;
}
static Texture[] GetFolderToTextures(Object folder)
{
var folderPath = AssetDatabase.GetAssetPath(folder);
var guids = AssetDatabase.FindAssets($"t:{typeof(Texture).Name}", new string[] { folderPath });
var assets = new Texture[guids.Length];
for (int i = 0; i < assets.Length; i++)
{
assets[i] = AssetDatabase.LoadAssetAtPath<Texture>(AssetDatabase.GUIDToAssetPath(guids[i]));
}
return assets;
}
폴더오브젝트에서 오디오 클립들을 반환
static AudioClip[] GetFolderToAudioAssets(Object folder)
{
var folderPath = AssetDatabase.GetAssetPath(folder);
var guids = AssetDatabase.FindAssets($"t:{typeof(AudioClip).Name}", new string[] { folderPath });
var audios = new AudioClip[guids.Length];
for (int i = 0; i < audios.Length; i++)
{
audios[i] = AssetDatabase.LoadAssetAtPath<AudioClip>(AssetDatabase.GUIDToAssetPath(guids[i]));
}
return audios;
}
파일 경로에서 오디오클립들을 반환
static AudioClip[] GetFolderToAudioFiles(string folderPath)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
var audios = new AudioClip[filePaths.Length];
for (int i = 0; i < audios.Length; i++)
{
audios[i] = LoadAudioClip(filePaths[i]);
audios[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
return audios;
}
코루틴 버전
IEnumerator GetFolderToAudioFilesListCo(params string[] folderPaths)
{
var audiosList = new List<AudioClip[]>();
var ienumerators = new IEnumerator[folderPaths.Length];
for (int i = 0; i < ienumerators.Length; i++)
{
ienumerators[i] = GetFolderToAudioFilesCo(folderPaths[i]);
StartCoroutine(ienumerators[i]);
}
for (int i = 0; i < ienumerators.Length; i++)
{
yield return new WaitUntil(() => ienumerators[i].Current.GetType() == typeof(AudioClip[]));
audiosList.Add((AudioClip[])ienumerators[i].Current);
}
yield return audiosList;
}
빠른버전
static AudioClip[] GetFolderToAudioFiles(string folderPath)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
var audios = new AudioClip[filePaths.Length];
string[] downloadLinks = Array.ConvertAll(filePaths, x => $"file://{x}");
var operations = new UnityWebRequestAsyncOperation[filePaths.Length];
var unityWebRequests = new UnityWebRequest[filePaths.Length];
for (int i = 0; i < audios.Length; i++)
{
unityWebRequests[i] = UnityWebRequestMultimedia.GetAudioClip(downloadLinks[i], AudioType.UNKNOWN);
operations[i] = unityWebRequests[i].SendWebRequest();
}
for (int i = 0; i < audios.Length; i++)
{
while (!operations[i].isDone)
{
Thread.Sleep(1);
}
if (unityWebRequests[i].isNetworkError)
{
Debug.LogError(unityWebRequests[i].error);
}
else
{
Debug.Log("LoadAudioClipSuccess");
}
audios[i] = DownloadHandlerAudioClip.GetContent(unityWebRequests[i]);
audios[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
return audios;
}
static AudioClip[] GetFolderToAudioFiles(string folderPath, string[] fileNames)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
filePaths = System.Array.FindAll(filePaths, x => fileNames.Contains(System.IO.Path.GetFileNameWithoutExtension(x)));
var audios = new AudioClip[filePaths.Length];
string[] downloadLinks = Array.ConvertAll(filePaths, x => $"file://{x}");
var operations = new UnityWebRequestAsyncOperation[filePaths.Length];
var unityWebRequests = new UnityWebRequest[filePaths.Length];
for (int i = 0; i < audios.Length; i++)
{
unityWebRequests[i] = UnityWebRequestMultimedia.GetAudioClip(downloadLinks[i], AudioType.UNKNOWN);
operations[i] = unityWebRequests[i].SendWebRequest();
}
for (int i = 0; i < audios.Length; i++)
{
while (!operations[i].isDone)
{
Thread.Sleep(1);
}
if (unityWebRequests[i].isNetworkError)
{
Debug.LogError(unityWebRequests[i].error);
}
else
{
Debug.Log("LoadAudioClipSuccess");
}
audios[i] = DownloadHandlerAudioClip.GetContent(unityWebRequests[i]);
audios[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
return audios;
}
비동기타입
static IEnumerator GetFolderToAudioFilesCo(string folderPath)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
var audios = new AudioClip[filePaths.Length];
string[] downloadLinks = System.Array.ConvertAll(filePaths, x => $"file://{x}");
var operations = new UnityWebRequestAsyncOperation[filePaths.Length];
var unityWebRequests = new UnityWebRequest[filePaths.Length];
for (int i = 0; i < audios.Length; i++)
{
unityWebRequests[i] = UnityWebRequestMultimedia.GetAudioClip(downloadLinks[i], AudioType.UNKNOWN);
operations[i] = unityWebRequests[i].SendWebRequest();
}
for (int i = 0; i < audios.Length; i++)
{
yield return new WaitUntil(() => operations[i].isDone);
if (unityWebRequests[i].isNetworkError)
{
Debug.LogError(unityWebRequests[i].error);
}
else
{
//Debug.Log("LoadAudioClipSuccess");
audios[i] = DownloadHandlerAudioClip.GetContent(unityWebRequests[i]);
audios[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
}
yield return audios;
}
불러올때
{
var co = GetFolderToAudioFilesCo(GetInfomationsFolderPath());
StartCoroutine(co);
yield return new WaitUntil(() => co.Current.GetType() == typeof(AudioClip[]));
infomationAudios = (AudioClip[])co.Current;
}
폴더오브젝트에서 텍스처에셋들을 반환
static Texture2D[] GetFolderToTextureAssets(Object folder)
{
var folderPath = UnityEditor.AssetDatabase.GetAssetPath(folder);
var guids = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(Texture2D).Name}", new string[] { folderPath });
var GUIDToAssetPaths = System.Array.ConvertAll(guids,x=> UnityEditor.AssetDatabase.GUIDToAssetPath(x));
var textures = System.Array.ConvertAll(GUIDToAssetPaths,x=> UnityEditor.AssetDatabase.LoadAssetAtPath<Texture2D>(x));
return textures;
}
폴더오브젝트에서 텍스처파일들을 반환
static Texture2D[] GetFolderToTexture2DFiles(string folderPath)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
var texture2Ds = new Texture2D[filePaths.Length];
for (int i = 0; i < texture2Ds.Length; i++)
{
texture2Ds[i] = LoadTexture2D(filePaths[i]);
texture2Ds[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
return texture2Ds;
}
빠른버전
static Texture2D[] GetFolderToTexture2DFilesHS(string folderPath)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
var texture2Ds = new Texture2D[filePaths.Length];
string[] downloadLinks = Array.ConvertAll(filePaths, x => $"file://{x}");
var operations = new UnityWebRequestAsyncOperation[filePaths.Length];
var unityWebRequests = new UnityWebRequest[filePaths.Length];
for (int i = 0; i < texture2Ds.Length; i++)
{
unityWebRequests[i] = UnityWebRequestTexture.GetTexture(downloadLinks[i]);
operations[i] = unityWebRequests[i].SendWebRequest();
}
for (int i = 0; i < texture2Ds.Length; i++)
{
while (!operations[i].isDone)
{
Thread.Sleep(1);
}
if (unityWebRequests[i].isNetworkError)
{
Debug.LogError(unityWebRequests[i].error);
}
else
{
Debug.Log("LoadAudioClipSuccess");
texture2Ds[i] = DownloadHandlerTexture.GetContent(unityWebRequests[i]);
texture2Ds[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
}
return texture2Ds;
}
비동기타입
IEnumerator GetFolderToSpriteFilesCo(string folderPath)
{
var co = GetFolderToTexture2DFilesCo(folderPath);
StartCoroutine(co);
yield return new WaitUntil(() => co.Current.GetType() == typeof(Texture2D[]));
var texture2Ds = (Texture2D[])co.Current;
var sprites = new Sprite[texture2Ds.Length];
for (int i = 0; i < texture2Ds.Length; i++)
{
sprites[i] = Sprite.Create(texture2Ds[i], new Rect(0, 0, texture2Ds[i].width, texture2Ds[i].height), Vector2.zero);
sprites[i].name = texture2Ds[i].name;
}
yield return sprites;
}
static IEnumerator GetFolderToTexture2DFilesCo(string folderPath)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
var texture2Ds = new Texture2D[filePaths.Length];
string[] downloadLinks = Array.ConvertAll(filePaths, x => $"file://{x}");
var operations = new UnityWebRequestAsyncOperation[filePaths.Length];
var unityWebRequests = new UnityWebRequest[filePaths.Length];
for (int i = 0; i < texture2Ds.Length; i++)
{
unityWebRequests[i] = UnityWebRequestTexture.GetTexture(downloadLinks[i]);
operations[i] = unityWebRequests[i].SendWebRequest();
}
for (int i = 0; i < texture2Ds.Length; i++)
{
yield return new WaitUntil(() => operations[i].isDone);
if (unityWebRequests[i].isNetworkError)
{
Debug.LogError(unityWebRequests[i].error);
}
else
{
Debug.Log("LoadAudioClipSuccess");
texture2Ds[i] = DownloadHandlerTexture.GetContent(unityWebRequests[i]);
texture2Ds[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
}
yield return texture2Ds;
}
오디오클립, 스프라이트 로드
static Sprite LoadAsset(string fileName, string folderPath, List<Sprite> listBuffer)
{
Sprite sprite = null;
sprite = listBuffer.Find(x => x.name.Trim().ToUpper() == fileName.Trim().ToUpper());
if (sprite == null)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
string filePath = System.Array.Find(filePaths, x => System.IO.Path.GetFileNameWithoutExtension(x).Trim().ToUpper() == fileName.Trim().ToUpper());
sprite = LoadSprite(filePath);
listBuffer.Add(sprite);
}
return sprite;
}
static AudioClip LoadAsset(string fileName, string folderPath, List<AudioClip> listBuffer)
{
AudioClip audioClip = null;
audioClip = listBuffer.Find(x => x.name.Trim().ToUpper() == fileName.Trim().ToUpper());
if (audioClip == null)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
string filePath = System.Array.Find(filePaths, x => System.IO.Path.GetFileNameWithoutExtension(x).Trim().ToUpper() == fileName.Trim().ToUpper());
audioClip = LoadAudioClip(filePath);
listBuffer.Add(audioClip);
}
return audioClip;
}
오디오클립, 스프라이트 언로드
void UnLoadAssets(List<Sprite> spriteList)
{
UnLoadAssets(spriteList.ToArray());
spriteList.Clear();
}
void UnLoadAssets(params Sprite[] sprites)
{
foreach (var sprite in sprites)
{
Destroy(sprite.texture);
Destroy(sprite);
}
}
void UnLoadAssets(List<AudioClip> audioList)
{
UnLoadAssets(audioList.ToArray());
audioList.Clear();
}
void UnLoadAssets(params AudioClip[] audios)
{
foreach (var audio in audios)
{
Destroy(audio);
}
}
void OnDestroy()
{
UnLoadAssets(spriteList);
UnLoadAssets(audioClipList);
}
폴더 경로에서 스프라이트들을 반환
static Sprite[] GetFolderToSpriteFiles(string folderPath)
{
string[] filePaths = System.IO.Directory.GetFiles(folderPath);
var sprites = new Sprite[filePaths.Length];
for (int i = 0; i < sprites.Length; i++)
{
sprites[i] = LoadSprite(filePaths[i]);
sprites[i].name = System.IO.Path.GetFileNameWithoutExtension(filePaths[i]);
}
return sprites;
}
static Sprite LoadSprite(string downloadLink)
{
var texture2D = LoadTexture2D(downloadLink);
var sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height), Vector2.zero);
sprite.name = System.IO.Path.GetFileNameWithoutExtension(downloadLink);
return sprite;
}
폴더오브젝트에서 스프라이트에셋들을 반환
static Sprite[] GetFolderToSpriteAssets(Object folder)
{
var folderPath = UnityEditor.AssetDatabase.GetAssetPath(folder);
var guids = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(Sprite).Name}", new string[] { folderPath });
var paths = System.Array.ConvertAll(guids, x => UnityEditor.AssetDatabase.GUIDToAssetPath(x));
var sprites = System.Array.ConvertAll(paths, x => UnityEditor.AssetDatabase.LoadAssetAtPath<Sprite>(x));
return sprites;
}
경로에서 Texture2D 가지고 오기
static Texture2D LoadTexture2D(string filePath)
{
Texture2D texture2D = Texture2D.blackTexture;
var fileData = System.IO.File.ReadAllBytes(filePath);
if (texture2D.LoadImage(fileData))
{
//성공
}
return texture2D;
}
//v2
static Texture2D LoadTexture2D(string filePath)
{
Texture2D texture2D = new Texture2D(1, 1);
if (System.IO.File.Exists(filePath)==false)
{
Debug.LogError($"{filePath}에 해당 파일 없음");
}
var fileData = System.IO.File.ReadAllBytes(filePath);
if (texture2D.LoadImage(fileData))
{
//성공
}
return texture2D;
}
경로에서 이미지 가져오기
//닷넷버전
public static Bitmap GetImage(string filePath)
{
return new Bitmap(filePath);
}
public static Bitmap[] GetImage(string[] filePath)
{
if (filePath != null)
{
Bitmap[] images = new Bitmap[filePath.Length];
for (int i = 0; i < filePath.Length; i++)
{
images[i] = new Bitmap(filePath[i]);
}
return images;
}
return null;
}
UnityWebRequest용 스트리밍 에셋 경로 (dataPath타입)
//안드로이드
string filePath=$"jar:file://{Application.dataPath}!/assets/{fileName}.zip";
UnityWebRequest용 스트리밍 에셋 경로 (내장타입)
var streamingAssetsPath = $"{Application.streamingAssetsPath}/{fileName}";
스트리밍에셋
public string fileName = "";
void Awake()
{
StartCoroutine(StreamingAssetCreate());
}
IEnumerator StreamingAssetCreate()
{
var extractFolderPath = $"{Application.persistentDataPath}/StreamingAssets";
var filePath = $"{extractFolderPath }/{fileName}";
var streamingAssetsPath = $"{Application.streamingAssetsPath}/{fileName}";
//if (!File.Exists(filePath))
{
if (Application.platform == RuntimePlatform.IPhonePlayer)
{
streamingAssetsPath = "file:///" + streamingAssetsPath;
}
UnityWebRequest unityWebRequest = UnityWebRequest.Get(streamingAssetsPath);
unityWebRequest.downloadedBytes.ToString();
var operation = unityWebRequest.SendWebRequest();
yield return new WaitUntil(()=>operation.isDone);
if (System.IO.Directory.Exists(extractFolderPath) == false)//폴더가 없으면 생성
{
System.IO.Directory.CreateDirectory(extractFolderPath);
}
File.WriteAllBytes(filePath, unityWebRequest.downloadHandler.data);
}
}
파일저장창
//System.IO.Stream s = null;
SaveFileDialog f = new SaveFileDialog();
f.Filter = "3D File(*.stl)|*.stl|Point Cloud(*.asc)|*.asc";
if (f.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("" + f.FileName);
//s = f.OpenFile()
유니티 경로를 윈도우 경로로 반환
public static string ConvertWindowFilePath(string unityFilePath)
{
string windowFilePath = null;
string assetsFolderPath = "Assets/";
if ((unityFilePath.Length >= assetsFolderPath.Length) && (unityFilePath.Substring(0, assetsFolderPath.Length) == assetsFolderPath))
{
windowFilePath = Application.dataPath+"/"+unityFilePath.Substring(assetsFolderPath.Length, unityFilePath.Length - assetsFolderPath.Length);
}
return windowFilePath;
}
파일이름 바꾸기 윈도우버전
void RenameFiles(string folderPath)
{
var filePaths = System.IO.Directory.GetFiles(folderPath);
foreach (var filePath in filePaths)
{
var fileName = System.IO.Path.GetFileNameWithoutExtension(filePath);
var filterName = fileName.Replace("_", "").Trim().ToLower();
var extension = System.IO.Path.GetExtension(filePath);
if (fileName != filterName)
{
var newFilePath = $"{folderPath}\\{filterName}{extension}";
Console.WriteLine($"파일이름 변경됨 {filePath}->{newFilePath}");
System.IO.File.Move(filePath, $"{folderPath}\\{filterName}{extension}");
}
}
}
파일이름 바꾸기
public void SetSpritesNames(UnityEngine.Object folder)
{
var folderPath = UnityEditor.AssetDatabase.GetAssetPath(folder);
var guids = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(Sprite).Name}", new string[] { folderPath });
var filterNames = new List<string>();
for (int i = 0; i < guids.Length; i++)
{
var assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
var fileName = System.IO.Path.GetFileNameWithoutExtension(assetPath);
var filterName = fileName.Replace("_", "").Trim().ToLower();
if (filterNames.Contains(filterName))
{
UnityEditor.AssetDatabase.MoveAssetToTrash(assetPath);
Debug.LogWarning("이름이 중복되어 삭제"+assetPath);
}
else
{
UnityEditor.AssetDatabase.RenameAsset(assetPath, filterName);
filterNames.Add(filterName);
}
}
}
csv파일이나 txt파일(텍스트 파일) 읽을때
주의점은 에셋번들로 호출시 항상 txt파일이 Resources폴더아래에 있어야 함
왜냐면 유니티는 txt파일 이런건 번들에 안 올리기 때문이다.
대신 Resource.Load 이딴건 안 써도 됨
TextAsset textAsset;
string text= textAsset.text;