데이터 관리(저장)을 이해하기 위해서 알아야 할 선수지식
객체 -> 파일로 바꾸는 것
[목적]
파일 -> 객체로 복원하는 것
데이터 저장방식
PlayerPrefs
게임 설정 -> 인게임에 크게 영향을 받지 않는 곳에 활용됨
사용 가능한곳
사용 불가능한곳
PlayerPrefs.SetFloat("키", value)
PlayerPrefs.SetInt("키", value)
PlayerPrefs.SetString("키", value)
PlayerPrefs.GetFloat("키", value)
PlayerPrefs.GetInt("키", value)
PlayerPrefs.GetString("키", value)
유니티 PlayerPrefs 저장 장소

CSV
ID,HP,ATK
1,100,10
2,200,20
-> 엑셀 -> 텍스트로 저장
"몬스터 스탯 -> 필드 변수 다 선언"
[문제]
[CSV 이점]
기획자가 데이터 값 수정 용이[CSV 단점]
Weapon
ㄴ Sword
ㄴ RareSword
Weapon,Sword,RareSword
Monster
ㄴ Skills
ㄴ Fire
ㄴ Ice
ID,Skill1,Skill2 ...
1,Fire,Ice
2,
[CSV 한계]
JSON
1) 하드코딩된 필드 변수
int level = 5;
2) 메모리 휘발
3) 서버 데이터
{
"gold": 500,
"items": ["sword", "potion"]
}
-> 문자열 -> 객체 보완해줘야함
public class Player : MonoBehaviour
{
public int _level;
public int _gold;
public string _path;
public void Save()
{
string json = JsonUtility.ToJson(this);
File.WriteAllText(_path, json);
}
}
-> Player.cs 게임 로직 담당
[위 코드의 문제점]
[역할 분리]
public class Player : MonoBehaviour
{
public int _level;
public int _gold;
}
-> 게임 플레이만 담당
public static class JsonHandler
{
// 파일 변환
public static string ToJson(Data data)
{
return JsonUtility.ToJson(data)
}
// 파일 저장
public static void Save(string path, string json)
{
File.WriteAlltext(path, json)
}
}
유니티에서 제공하는 JSON 2가지
[특징]
[장점]
[한계점]
Package Manager git URL 설치:
com.unity.nuget.newtonsoft-json
JsonUtility는 Unity 저장 규칙 따름 (Inspector에 뜨나/안뜨나)Newtonsoft JSON Unity 규칙 무관 -> C# 객체를 직접 JSON 바꿈CSVNewtonsoft JSONJsonUtility[사용처]
-> C# 객체가 JSON 변환해주기 때문에 JsonUtility가 제공하지 않는 것들도 제공함
-> Unity에서 제공하는 직렬화 객체들만 가능 = Inspector에서 보이는지 여부
ScriptableObject

public class TreeModel : MonoBehaviour
{
Mesh _mesh;
Texture _bark;
Texture _leaves;
}
public class Tree
{
TreeModel _model;
Vector3 _position;
double _height;
double _width;
Color _barkTint;
Color _leafTink;
}

CSV - JSON - ScriptableObject