유니티 & Json

Json으로 세이브 파일 만들기, 로드

ruripanda 2024. 10. 24. 22:27

지난글에 이어서 작성

 

세이브파일 작성법

 

using UnityEngine;
using System.IO;//<<파일 입출력
using System.Text;//<<텍스트 관리자
using Newtonsoft.Json;//<<뉴튼소프트 Json사용

public class JsonSaveLoader : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        FileStream stream = new FileStream(Application.dataPath + "/test.json", FileMode.OpenOrCreate);//세이브 파일 경로에 .json으로 만들기
        JsonTestClass jTest1 = new JsonTestClass();//새 항목 만들기
        string jsonData = JsonConvert.SerializeObject(jTest1);//문자화
        byte[] data = Encoding.UTF8.GetBytes(jsonData);//파일 인코딩 UTF8으로 생성
        stream.Write(data, 0, data.Length);
        stream.Close();//파일 스트림 작성
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

짠하고 경로에 세이브 파일이 만들어 진다
비주얼스튜디오로 확인한 텍스트파일로 세이브된 데이터

 

파일을 로드하는 법

 

 

using UnityEngine;
using System.IO;//<<파일 입출력
using System.Text;//<<텍스트 관리자
using Newtonsoft.Json;//<<뉴튼소프트 Json사용

public class JsonSaveLoader : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        FileStream stream = new FileStream(Application.dataPath + "/test.json", FileMode.Open);
        //파일모드를 오픈으로 설정
        byte[] data = new byte[stream.Length];
        stream.Read(data, 0, data.Length);//생성된 파일스트림에서 리드로 
        stream.Close();
        string jsonData = Encoding.UTF8.GetString(data);//인코딩을 잡아준다
        JsonTestClass jTest2 = JsonConvert.DeserializeObject<JsonTestClass>(jsonData);
        //이제 딕시리얼 라이즈하고
        jTest2.Prinnt();//출력해준다
    }

정상적으로 파일이 로드되어 오브젝트로 콘솔에 출력된다

이렇게 파일을 로드해서 덮어씌우는 식으로 세이브파일을 만든다

 

구글에서 Json To C#이라고 치면 

친절하게 문법 검사기가 나온다