-
13주차 - 맵 데이터 세이브, 및 로드Unity/Unity 스파르타 2024. 3. 11. 20:21728x90
1. 맵 데이터를 리소스폴더에 Json 파일로 저장하기
2. 저장한 데이터 불러오기
3. 맵 에디터에서 새로 만든 맵인지, 불러온 맵인지에 따라 저장 로직을 다르게 만들기
1. 맵 데이터를 리소스폴더에 Json 파일로 저장하기
파일 저장할 경로 구하기
Application.dataPath 를 사용해 현재 실행된 프로젝트의 Asset 폴더의 절대경로를 알 수 있습니다.
folderPath = Path.Combine(Application.dataPath, "Resources/MapDat");
맵에 데이터를 Json 파일로 변환해 저장합니다.
void CreateJsonFile() { Map map = new Map(mapID, mapTileDataList, playerSpawnPosition, playerExitPosition, new Vector2(width, height)); string json = JsonUtility.ToJson(map); string filePath = Path.Combine(folderPath, $"{map.mapID}.json"); File.WriteAllText(filePath, json); UnityEditor.AssetDatabase.Refresh(); }
UnityEditor.AssetDatabase.Refresh();
리프레쉬는 유니티에서 변경된 파일을 감지해 에셋 데이터베이스를 업데이트 해주는 함수입니다. 써주지 않으면 런타임 환경에서 사용할 수가 없습니다.
public void LoadJsonFile() { foreach(TextAsset json in Resources.LoadAll<TextAsset>("MapDat")) { Map map = JsonUtility.FromJson<Map>(json.text); mapDictionary.Add(map.mapID, map); Debug.Log(map.mapID); } }
리소스폴더의 로드해올 경로에 있는 파일을 모두 가져와 딕셔너리에 넣어줍니다.
새로운 맵을 만들때 저장 경로에 똑같은 이름이 있으면 자동으로 뒤에 숫자를 붙여 데이터를 저장해줍니다
if(mapEditorType == MapEditorType.New ){ string path = Path.Combine(folderPath, $"{mapID}.json"); bool fileExists = File.Exists(path); while (fileExists) { int num = 1; path = Path.Combine(folderPath, $"{mapID}{num}.json"); if (!File.Exists(path)) { mapID = $"{mapID}{num}"; fileExists = false; } num++; }
728x90'Unity > Unity 스파르타' 카테고리의 다른 글
13주차 - 맵 데이터화.. (0) 2024.03.15 13주차 - 맵.. (0) 2024.03.14 12주 - 최종 프로젝트(2D) (0) 2024.03.06 11주차 - 패시브 스킬 트리 구현 (0) 2024.03.02 10주차 - 개인 심화 3D(NavMeshAgent.path.corners, NavMeshSurface , Animation Curve) (0) 2024.02.22