본문 바로가기

Unity/Unity 스파르타

13주차 - 맵 데이터 세이브, 및 로드

728x90

 

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