유니티

Json 데이터 저장

잼잼재미 2024. 4. 3. 20:48

Json (JavaScript Object Notation)


  • 데이터를 저장하거나 교환하는데 사용되는 경량의 데이터 교환 형식
  • 텍스트 기반의 데이터 형식
  • 키-값 쌍으로 이루어진 데이터 객체와 배열을 포함
  • 유니티에서 JSON Utility 클래스를 사용해서 오브젝트 데이터를 쉽게 다룰 수 있음
  • class 자체를 배열이나 리스트로 사용하기 위해서는 DataWrapper class를 만들어서 사용
  • 일반적으로 DataManager에서 구현
  • string, int, float 처럼 입력 가능한 데이터만 저장 가능
    • 드래그 드롭 데이터는 저장 X                                                                                                         

 

 

사용 방법


1. 스크립트 작성

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

[System.Serializable]
public class GameData
{
    [Header("GameData")]
    public int Satge = 1;
    public int Coin = 0;
    public int SkillDrawCount = 0;

    [Header("Sound")]
    public float BGMVolume = 0;
    public float SFXVolume = 0;
}

[System.Serializable]
public class DataWrapper
{
    public EnemyData[] MeleeEnemyData;
}

[System.Serializable]
public class EnemyData
{
    public enum AttackType
    {
        Melee,
        Ranged,
    }

    [Header("Common Stats")]
    public string Tag;
    public AttackType Type;
    public float Hp;
    public float Speed;
    public float Atk;
    public int Price;

    [Header("Ranged Stats")]
    public string BulletTag;
    public float BulletSpeed;
    public float Distance;
    public Vector3 BulletPosition;
}

public class DataManager : MonoBehaviour
{
    public GameData GameData;

    public void Init()
    {
        
    }

    public void Release()
    {

    }

     [ContextMenu("To Json Data")] // 컴포넌트 메뉴에 아래 함수를 호출하는 To Json Data 라는 명령어가 생성됨
    void SaveGameDataToJson()
    {
  		if (Application.platform == RuntimePlatform.WebGLPlayer || Application.platform == RuntimePlatform.Android)
        {
            string jsonData = JsonUtility.ToJson(GameData, true);
            string path = Path.Combine(Application.persistentDataPath, "GameData.json");
            File.WriteAllText(path, jsonData);
        }
        else
        {
            string jsonData = JsonUtility.ToJson(GameData, true);
            string path = Path.Combine(Application.dataPath, "GameData.json");
            File.WriteAllText(path, jsonData);
        }
    }

    [ContextMenu("From Json Data")]
    void LoadGameDataFromJson()
    {
        if(Application.platform == RuntimePlatform.WebGLPlayer || Application.platform == RuntimePlatform.Android)
        {
            string path = Path.Combine(Application.persistentDataPath, "GameData.json");
            string jsonData = File.ReadAllText(path);
            GameData = JsonUtility.FromJson<GameData>(jsonData);
        }
        else
        {
            string path = Path.Combine(Application.dataPath, "GameData.json");
            string jsonData = File.ReadAllText(path);
            GameData = JsonUtility.FromJson<GameData>(jsonData);
        }
    }
    
    // DataWrapper
    [ContextMenu("To Json DataWrapper")]
    void SaveDataWrapperToJson()
    {
        if (Application.platform == RuntimePlatform.WebGLPlayer || Application.platform == RuntimePlatform.Android)
        {
            string jsonData = JsonUtility.ToJson(DataWrapper, true);
            string path = Path.Combine(Application.persistentDataPath, "DataWrapper.json");
            File.WriteAllText(path, jsonData);
        }
        else
        {
            string jsonData = JsonUtility.ToJson(DataWrapper, true);
            string path = Path.Combine(Application.dataPath, "DataWrapper.json");
            File.WriteAllText(path, jsonData);
        }
    }

    [ContextMenu("From Json DataWrapper")]
    void LoadDataWrapperFromJson()
    {
        if (Application.platform == RuntimePlatform.WebGLPlayer || Application.platform == RuntimePlatform.Android)
        {
            string path = Path.Combine(Application.persistentDataPath, "DataWrapper.json");
            string jsonData = File.ReadAllText(path);
            DataWrapper = JsonUtility.FromJson<DataWrapper>(jsonData);
        }
        else
        {
            string path = Path.Combine(Application.dataPath, "DataWrapper.json");
            string jsonData = File.ReadAllText(path);
            DataWrapper = JsonUtility.FromJson<DataWrapper>(jsonData);
        }

    }
    
    // 데이터 저장 시, 함수 호출
    public void DataSave()
    {
        SaveGameDataToJson();
        SaveDataWrapperToJson();
    }

	// 데이터 불러오기 시, 함수 호출
    public void DataLoad()
    {
        LoadGameDataFromJson();
        LoadDataWrapperFromJson();
    }
}

 

 

2. 폴더 생성

 

지정한 경로에 맞게 폴더를 생성

* 폴더를 생성해서 경로를 지정하는 경우, Window 빌드 시, 경로 오류가 발생, 폴더를 생성하지 않고 할 것!

 

 

3. 저장/불러오기

 

스크립트 메뉴 항목을 선택해서 저장/불러오기가 가능

* 단, 변경된 데이터가 없으면 저장이 안됨

'유니티' 카테고리의 다른 글

구글 플레이 업로드  (0) 2024.04.19
앱 이름 한글 설정  (0) 2024.04.19
화면 깜빡이기  (0) 2024.03.27
2D 화살 구현 (포물선 운동)  (0) 2024.03.25
SpawnSystem 구현  (1) 2024.03.21