JSON - 직렬화
- 사용하고있는 데이터들을 저장, 전송하기 위해 가공한 형태
- 다른것 CSV, ini, XML 등등
- 옛날에는 CSV처럼 간단한 , 를 쓰는 데이터 전송 방식이였는데 JSON은 현대시대로봤을때 몸집이 크고 질소가 많아도 인터넷의 속도가 높아졌기 때문에 제약받지 않는다.
using Platformer.Mechanics;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class JsonTest : MonoBehaviour
{
[System.Serializable]
public class ObjectData
{
public Vector3 pos;
public string patrolPathName;
public float maxSpeed;
}
[System.Serializable]
public class ObjectList
{
public List<ObjectData> list = new List<ObjectData>();
}
[SerializeField]
string filePath;
enum State
{
SAVE,
LOAD
}
[SerializeField]
State state;
[SerializeField]
GameObject top;
[SerializeField]
GameObject prefab;
// Start is called before the first frame update
void Start()
{
filePath = Path.Combine(Application.streamingAssetsPath, "objData.json");
if (state == State.SAVE)
{
SaveData();
}
else
{
LoadData();
}
}
public void LoadData()
{
if (File.Exists(filePath))
{
// 파일에서 JSON 읽고 객체로 변환
string json = File.ReadAllText(filePath);
ObjectList objectList = JsonUtility.FromJson<ObjectList>(json);
foreach (var i in objectList.list)
{
var enemy = Instantiate(prefab, top.transform);
enemy.transform.position = i.pos;
if (i.patrolPathName != "")
{
var patrol = GameObject.Find(i.patrolPathName).GetComponent<PatrolPath>();
enemy.GetComponent<EnemyController>().path = patrol;
}
enemy.GetComponent<AnimationController>().maxSpeed = i.maxSpeed;
}
Debug.Log("\\nData loaded: " + json);
}
else
{
Debug.Log("No save file found.");
}
}
public void SaveData()
{
var list = GameObject.FindGameObjectsWithTag("Enemy");
ObjectList objectList = new ObjectList();
foreach (var obj in list)
{
ObjectData data = new ObjectData();
data.pos = obj.transform.position;
var patrolPath = obj.GetComponent<EnemyController>().path;
data.patrolPathName = patrolPath == null ? "" : patrolPath.name;
data.maxSpeed = obj.GetComponent<AnimationController>().maxSpeed;
objectList.list.Add(data);
}
// JSON 형식으로 변환하고 파일로 저장
string json = JsonUtility.ToJson(objectList, true);
// 경로상 폴더 없으면 폴더 생성
var path = Path.GetDirectoryName(filePath);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
File.WriteAllText(filePath, json);
Debug.Log("Data saved: " + json);
}
}