Get it on Google Play


Wm뮤 :: 'Unity' 카테고리의 글 목록 (19 Page)

블로그 이미지
가끔 그림그리거나 3D모델링하거나
취미로 로봇만드는
퇴직한 전자과 게임프로그래머
2020.3.48f1 , 2022.3.6f1 주로 사용
모카쨩
@Ahzkwid

Recent Comment

Archive


2020. 8. 20. 15:54 Unity/C#

파일을 다운로드

    public string url;
    public string fileName;
    public string fileType;
    IEnumerator DownloadFile()
    {
        string filePath= $"{Application.persistentDataPath}/{fileName}";
        if( (fileType != null)&& (fileType.Trim() != "") )
        {
            filePath += $".{fileType}";
        }
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
        yield return unityWebRequest.SendWebRequest();
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            File.WriteAllBytes(filePath, unityWebRequest.downloadHandler.data);
        }
    }

 

 

V2




    /// <summary>
    /// 다운 다되면 파일경로를 반환
    /// </summary>
    /// <param name="downloadlink"></param>
    /// <param name="filePath"></param>
    /// <returns></returns>
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        Debug.Log($"Download:{downloadlink}");
        {
            DOWNLOAD_RETRY:;
            {
                var unityWebRequest = UnityWebRequest.Get(downloadlink);
                var operation = unityWebRequest.SendWebRequest();
                yield return new WaitUntil(() => operation.isDone);

                if (unityWebRequest.isNetworkError)
                {
                    Debug.LogError(unityWebRequest.error);
                    yield return new WaitForSeconds(3f);
                    goto DOWNLOAD_RETRY;
                }
                else
                {
                    Debug.Log(filePath);

                    var folderPath = System.IO.Path.GetDirectoryName(filePath);
                    Debug.Log(folderPath);
                    if (System.IO.Directory.Exists(folderPath) == false)//폴더가 없으면 생성
                    {
                        System.IO.Directory.CreateDirectory(folderPath);
                    }
                    System.IO.File.WriteAllBytes(filePath, unityWebRequest.downloadHandler.data);
                }
            }
        }
        yield return filePath;
    }

 

 

 

 

 

DownloadHandlerFile 방식 

메모리를 딱 필요한만큼만 쓴다. 위에는 2배사용

V3



    List<string> downloadList = new List<string>();
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        downloadList.Add(downloadlink);

        DOWNLOADRETRY:;
        {
            UnityWebRequest unityWebRequest = UnityWebRequest.Get(downloadlink);
            unityWebRequest.downloadHandler = new DownloadHandlerFile(filePath);

            var operation = unityWebRequest.SendWebRequest();
            yield return new WaitUntil(() => operation.isDone);

            if (unityWebRequest.isNetworkError)
            {
                Debug.LogError(unityWebRequest.error);
                yield return new WaitForSeconds(1f);
                goto DOWNLOADRETRY;
            }
            else
            {
                Debug.Log(filePath);
            }
        }
        downloadList.Remove(downloadlink);
    }

 

V1~V2

더보기
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(downloadlink);
        unityWebRequest.downloadHandler = new DownloadHandlerFile(filePath);
        var operation = unityWebRequest.SendWebRequest();
        while (!operation.isDone)
        {
            yield return new WaitForSeconds(0.01f);
        }
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            Debug.Log(filePath);
        }
    }

 

 

 

V2

List<String> DownloadList = new List<String>();
    IEnumerator DownloadFile(string downloadlink, string filePath)
    {
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(downloadlink);
        unityWebRequest.downloadHandler = new DownloadHandlerFile(filePath);

        DownloadList.Add(downloadlink);
        DOWNLOADRETRY:;
        var operation = unityWebRequest.SendWebRequest();
        while (!operation.isDone)
        {
            yield return new WaitForSeconds(0.01f);
        }
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
            yield return new WaitForSeconds(1f);
            goto DOWNLOADRETRY;
        }
        else
        {
            Debug.Log(filePath);
        }
        DownloadList.RemoveAt(DownloadList.FindIndex(0, DownloadList.Count, x => x == downloadlink));
    }

 

 

 

 

 

 

HTML 다운로드

    public string urlSample= "https://wmmu.tistory.com/";
    IEnumerator DownloadHTML(string url)
    {
        UnityWebRequest unityWebRequest;
        unityWebRequest = UnityWebRequest.Get(url);
        yield return unityWebRequest.SendWebRequest();
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            Debug.Log(unityWebRequest.downloadHandler.text);
        }
    }

 

 

 

오디오 파일 로드

//전용 세이브 폴더 참조시에는
//$"file://{UnityEngine.Application.persistentDataPath}/Audio.mp3";
static AudioClip LoadAudioClip(string downloadLink)
{
    var fileName= downloadLink;
    if (System.IO.File.Exists(downloadLink))
    {
        downloadLink = $"file://{downloadLink}";
        fileName = System.IO.Path.GetFileNameWithoutExtension(downloadLink);
    }
    UnityWebRequest unityWebRequest = UnityWebRequestMultimedia.GetAudioClip(downloadLink, AudioType.UNKNOWN);

    var operation = unityWebRequest.SendWebRequest();
    while (!operation.isDone)
    {
        Thread.Sleep(1);
    }
    if (unityWebRequest.isNetworkError)
    {
        Debug.LogError(unityWebRequest.error);
    }
    else
    {
        //Debug.Log("LoadAudioClipSuccess");
    }
    var clip = DownloadHandlerAudioClip.GetContent(unityWebRequest);
    clip.name = fileName;
    return clip;
}

 

 

 

 

캐시 테스트

    public string url;
    public string cookie;
    public string fileName;
    public string fileType;
    IEnumerator DownloadFile()
    {
        string filePath = $"{Application.persistentDataPath}/{fileName}";
        if ((fileType != null) && (fileType.Trim() != ""))
        {
            filePath += $".{fileType}";
        }
        UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
        if (string.IsNullOrWhiteSpace(cookie)==false)
        {
            unityWebRequest.SetRequestHeader("Cookie", cookie);
        }
        yield return unityWebRequest.SendWebRequest();
        if (unityWebRequest.isNetworkError)
        {
            Debug.LogError(unityWebRequest.error);
        }
        else
        {
            Debug.Log(unityWebRequest.downloadHandler.text);
            //File.WriteAllBytes(filePath, unityWebRequest.downloadHandler.data);
        }
    }
    // Start is called before the first frame update
    void Start()
    {
        StartCoroutine(DownloadFile());
    }

'Unity > C#' 카테고리의 다른 글

c# MD5  (0) 2020.08.25
형변환 모음  (0) 2020.08.11
유니티 씬 계열 함수 모음  (0) 2020.07.30
posted by 모카쨩
2020. 8. 19. 16:26 Unity

 

 

 

 

 

 

 

비주얼스튜디오 2019는 여기에 있다

C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe

 

 

 

 

가 아니고 사실 이렇게 경로를 지정해주면 안되고 비주얼 스튜디오 인스톨러를 이용해서 한번 더 설치해주면 저기에 알아서 비주얼 스튜디오 커뮤니티라고 뜬다

 

 

 

 

 

 

 

 

'Unity' 카테고리의 다른 글

유니티 Mask  (0) 2020.09.24
유니티 콜라보레이트 클라우드  (0) 2020.08.10
This mesh uses 'Multiple Canvas Renderers' for correct rendering.  (0) 2020.08.05
posted by 모카쨩
2020. 8. 11. 16:58 Unity/C#

 

 

일반적으로 사용하는 타입

var 변수= (타입)오브젝트;

 

가독성을 위해 간간히 쓰이는 타입, 괄호가 너무 많을때 사용함

var 변수= 오브젝트 as 타입

 

옛날방식

int 변수=int.Parse("1");

 

 

 

'Unity > C#' 카테고리의 다른 글

UnityWebRequest  (0) 2020.08.20
유니티 씬 계열 함수 모음  (0) 2020.07.30
C# 파일관련 함수들  (0) 2020.07.30
posted by 모카쨩
2020. 8. 10. 11:05 Unity

 

 

 

 

https://dashboard.unity3d.com/landing

 

 

 

-추가 2020-12-30 : 

수정할때라서 그런지는 몰라도 이렇게 바뀌었다

 

 

 

 

 

 

 

 

 

 

 

 

 

 

매니저는 파일이름수정 권한이 없다

 

 

참여한측 화면

 

눌러

 

 

 

 

 

 

 

dashboard.unity3d.com/collaborate

초대 받았는데도 안되면 활성화를 해줘야한다

posted by 모카쨩
2020. 8. 5. 10:25 Unity

This mesh uses 'Multiple Canvas Renderers' for correct rendering. Consider packing attachments to a single atlas page if possible

 

 

 

 

 

'Unity' 카테고리의 다른 글

유니티 콜라보레이트 클라우드  (0) 2020.08.10
유니티 함수 연동 안될때  (0) 2020.08.03
유니티 스파인 오류 모음  (0) 2020.07.24
posted by 모카쨩
2020. 8. 3. 11:35 Unity

'Unity' 카테고리의 다른 글

This mesh uses 'Multiple Canvas Renderers' for correct rendering.  (0) 2020.08.05
유니티 스파인 오류 모음  (0) 2020.07.24
유니티 로그캣  (0) 2020.06.29
posted by 모카쨩
2020. 7. 30. 19:19 Unity/C#

씬 이동시에도 파괴 안됨

DontDestroyOnLoad(gameObject);

 

 

 

씬로드 v1~v5

더보기

씬 로드 Object형(에디터상에서만 먹힘)

    public void LoadScene(Object SceneFile)
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene(SceneFile.name);
    }

 

 

유니티가 씬 로드에 있어 워낙 불친절한놈이라 아래처럼 수동으로 짜줘야함

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(ScenePicker), true)]
public class ScenePickerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        var picker = target as ScenePicker;
        var oldScene = AssetDatabase.LoadAssetAtPath<SceneAsset>(picker.scenePath);

        serializedObject.Update();

        EditorGUI.BeginChangeCheck();
        var newScene = EditorGUILayout.ObjectField("scene", oldScene, typeof(SceneAsset), false) as SceneAsset;

        if (EditorGUI.EndChangeCheck())
        {
            var newPath = AssetDatabase.GetAssetPath(newScene);
            var scenePathProperty = serializedObject.FindProperty("scenePath");
            scenePathProperty.stringValue = newPath;
        }
        serializedObject.ApplyModifiedProperties();
    }
}
public class ScenePicker : MonoBehaviour
{
    [SerializeField]
    public string scenePath;
}

 

 

축약버전

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(ScenePicker), true)]
public class ScenePickerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
		{
          var target_ScenePicker = target as ScenePicker;
          var oldScene = AssetDatabase.LoadAssetAtPath<Object>(target_ScenePicker.scenePath);
          var newScene = EditorGUILayout.ObjectField(nameof(target_ScenePicker.scenePath), oldScene, typeof(Object), false);
          target_ExcelReader.scenePath = AssetDatabase.GetAssetPath(newScene);
        }
        serializedObject.ApplyModifiedProperties();
    }
}
public class ScenePicker : MonoBehaviour
{
    [SerializeField]
    public string scenePath;
}

 

 

그냥 오브젝트를 추가한 버전

이딴 버전을 왜 만들었냐 하면 인스펙터상에서 파일을 추적할때는 오브젝트를 써야하고

인 게임에서 파일을 추적할때는 string을 써야하기 때문이다

[HideInInspector]는 쓰면 안 된다. 값이 날아가 버리기 때문에(아닌가?)

using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(ScenePicker), true)]
public class ScenePickerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        serializedObject.Update();
		{
            var target_ScenePicker = target as ScenePicker;
            if(target_ScenePicker.scene!=null)
            {
                target_ScenePicker.scenePath = AssetDatabase.GetAssetPath(target_ScenePicker.scene);
            }
        }
        serializedObject.ApplyModifiedProperties();
    }
}
public class ScenePicker : MonoBehaviour
{
    public Object scene;
    public string scenePath;
}

위랑 똑같은데 Path가 아닌 이름을 쓰는 버전

어차피 이래해도 작동은 잘 된다. 결국 원점회귀

using UnityEngine;


#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(ScenePicker), true)]
public class ScenePickerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
        serializedObject.Update();
		{
            var target_ScenePicker = target as ScenePicker;
            if(target_ScenePicker.scene!=null)
            {
                target_ScenePicker.sceneName = target_ScenePicker.scene.name;
            }
        }
        serializedObject.ApplyModifiedProperties();
    }
}
#endif
public class ScenePicker : MonoBehaviour
{
#if UNITY_EDITOR
    public SceneAsset scene;
#endif
    [HideInInspector]
    public string sceneName;
}

 

 v5

using UnityEngine;


#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(ScenePicker), true)]
public class ScenePickerEditor : Editor
{
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        {
            DrawPropertiesExcluding(serializedObject, nameof(ScenePicker.sceneName));

            var scene = serializedObject.FindProperty(nameof(ScenePicker.scene));
            var sceneName = serializedObject.FindProperty(nameof(ScenePicker.sceneName));
            sceneName.stringValue = scene.objectReferenceValue.name;
        }
        serializedObject.ApplyModifiedProperties();
    }
}
#endif
public class ScenePicker : MonoBehaviour
{
#if UNITY_EDITOR
    public SceneAsset scene;
#endif
    [HideInInspector]
    public string sceneName;
}

 

 

 

씬로드 v6

v5랑 동일하지만 바로바로 사용하기 편하게 함수내장시켰다

using UnityEngine;


#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(SceneLoader), true)]
public class SceneLoaderEditor : Editor
{
    public override void OnInspectorGUI()
    {
        serializedObject.Update();
        {
            DrawPropertiesExcluding(serializedObject, nameof(SceneLoader.sceneName));

            var scene = serializedObject.FindProperty(nameof(SceneLoader.scene));
            var sceneName = serializedObject.FindProperty(nameof(SceneLoader.sceneName));
            sceneName.stringValue = scene.objectReferenceValue.name;
        }
        serializedObject.ApplyModifiedProperties();
    }
}
#endif
public class SceneLoader : MonoBehaviour
{
#if UNITY_EDITOR
    public SceneAsset scene;
#endif
    [HideInInspector]
    public string sceneName;

    public void LoadScene()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
    }
}

 

 

씬들로드

#if UNITY_EDITOR
using UnityEditor;


[CustomEditor(typeof(GotoRandomScene), true)]
public class GotoRandomSceneInspecter : Editor
{
    public override void OnInspectorGUI()
    {
        EditorGUI.BeginChangeCheck();
        serializedObject.Update();
        {
            DrawPropertiesExcluding(serializedObject, nameof(GotoRandomScene.sceneNames));
        }
        serializedObject.ApplyModifiedProperties();
        if (EditorGUI.EndChangeCheck())
        {
            var picker = target as GotoRandomScene;
            picker.sceneNames = System.Array.ConvertAll(picker.scenes, x => x.name);
        }
    }
}
#endif



public class GotoRandomScene : MonoBehaviour
{
    [Header("랜덤룸으로 이동함")]
#if UNITY_EDITOR
    public UnityEditor.SceneAsset[] scenes;
#endif
    public string[] sceneNames;
}

 

 

 

 

 

현재 씬 이름

UnityEngine.SceneManagement.SceneManager.GetActiveScene().name

 

 

 

 

환경은 그대로 두고 맵만 불러올떄 사용한거

var sceneName = gotoRandomScene.sceneNames[sceneNumber];

for (int i = 0; i < SceneManager.sceneCount; i++)
{
    var scene = SceneManager.GetSceneAt(i);

    //없는 이름 스킵
    if (System.Array.Find(gotoRandomScene.sceneNames, x => x == scene.name) == null)
    {
        continue;
    }

    //원하는 씬이 맞음
    if (sceneName == scene.name)
    {
        return;
    }

    //원하는 씬이 아님
    {
        SceneManager.UnloadSceneAsync(scene);
    }
}
//원하는 씬이 없음
{
    DestroyAll();
    UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName, LoadSceneMode.Additive);
}
/*
if (sceneName != UnityEngine.SceneManagement.SceneManager.GetActiveScene().name)
{
    DestroyAll();
    UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName, LoadSceneMode.Additive);
}
*/

'Unity > C#' 카테고리의 다른 글

형변환 모음  (0) 2020.08.11
C# 파일관련 함수들  (0) 2020.07.30
c# Array(배열)관련  (0) 2020.07.29
posted by 모카쨩
2020. 7. 30. 17:31 Unity/C#

 

 

프로젝트 내 에셋들의 파일주소는 다음과 같이 얻어야 한다 안드로이드에서는 못 쓴다.

앞부분에 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(@"\","/"));

 

 

 

파일 정보 (파일시간, 파일용량 등)

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 AudioClip[] GetFolderToAudioAssets(Object folder)
    {
        var folderPath = AssetDatabase.GetAssetPath(folder);
        var filePathAudioClips = AssetDatabase.FindAssets($"t:{typeof(AudioClip).Name}", new string[] { folderPath });
        var audios = new AudioClip[filePathAudioClips.Length];
        for (int i = 0; i < audios.Length; i++)
        {
            audios[i] = AssetDatabase.LoadAssetAtPath<AudioClip>(AssetDatabase.GUIDToAssetPath(filePathAudioClips[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 filePathTextures = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(Texture2D).Name}", new string[] { folderPath });
    var GUIDToAssetPaths = System.Array.ConvertAll(filePathTextures,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 filePathSprites = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(Sprite).Name}", new string[] { folderPath });
        var GUIDToAssetPaths = System.Array.ConvertAll(filePathSprites, x => UnityEditor.AssetDatabase.GUIDToAssetPath(x));
        var sprites = System.Array.ConvertAll(GUIDToAssetPaths, 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 filePathSpriteDatas = UnityEditor.AssetDatabase.FindAssets($"t:{typeof(Sprite).Name}", new string[] { folderPath });
        var filterNames = new List<string>();
        for (int i = 0; i < filePathSpriteDatas.Length; i++)
        {
            var assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(filePathSpriteDatas[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;

 

'Unity > C#' 카테고리의 다른 글

유니티 씬 계열 함수 모음  (0) 2020.07.30
c# Array(배열)관련  (0) 2020.07.29
유니티 키보드  (0) 2020.07.28
posted by 모카쨩

  • total
  • today
  • yesterday

Recent Post

저사양 유저용 블로그 진입