유니티 게임 종료 시 데이터 저장과 불러오기(with json)

최명구·2021년 10월 19일
0

유니티 공부하자

목록 보기
6/7

이전 글인 씬 변경 시에 데이터 저장에 이어서 게임(세션) 종료 시에 json형식으로 데이터 저장을 하는 법을 알아보자.

유니티에는 [Serializable] class를 json형식으로 바꿔주는 JsonUtility라는 클래스가 있다.
이 클래스를 통해 간단한 데이터를 저장 하는 메소드와 불러오는 클래스를 구현해보자.


[System.Serializable]
class Data
{
    public Color color;
    public Vector3 pos;
    public int stage;
}
public void SaveData(Color color, Vector3 position, int stage)
{
	Data data = new Data();
	data.color = color;
	data.pos = position;
	data.stage = stage;
    
	string json = JsonUtility.ToJson(data);
    
	File.WriteAllText(Application.persistentDataPath + "/savefile.json",json);
}
public Data LoadData()
{
	string path = Application.persistentDataPath + "/savefile.json";
	if (File.Exists(path))
	{
		string json = File.ReadAllText(path);
		Data data = JsonUtility.FromJson<Data>(json);
  		return data;
	}
}

아주 간단하게 json형식으로 데이터를 저장하고 불러올 수 있다.
+Application.persistentDataPath의 위치는 플랫폼 별로 다르다. 자세한 내용은 공식 문서 참조 https://docs.unity3d.com/ScriptReference/Application-persistentDataPath.html?_ga=2.41905634.1730565472.1634532602-1641837481.1632464210

profile
게임 개발 공부하는 사람

0개의 댓글