본문 바로가기
개발/Unity

Unity)로컬 이어하기 작업(Save & Load - BinaryFoatter)

by 테샤르 2020. 7. 29.

로컬 이어하기 작업(Save & Load - BinaryFoatter)

개발을 진행하다 보면 중간에 저장할 때 로드와 이어하기에 대한 작업을 진행하는 경우가 많다.

저장할 메모리를 Binary로 쓰고 읽는 방식을 사용하면 매우 편리하다.

Unity의 Life Cycle 중에서 OnApplicationQuit 하는 순간에 현재 저장된 데이터를 Save 하고 다시 앱을 실행하는 경우에 저장된 데이터가 존재하면 이어하는 처리를 진행했다.

샘플 코드 예제는 다음과 같다.

/*

*       설명 : 
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;

[Serializable]
public class InfoSave
{
    public List<int> list = null;
}


public class SaveManager : Singleton<SaveManager>
{
    private InfoSave data = null;
    #region Private Method

    #endregion
    #region Public Method

    public void Save()
    {
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
        InfoSave data = new InfoSave();
        data.list = new List<int>();
        for(int i = 0; i< 5;i++){
            data.list.Add(UnityEngine.Random.Range(1,100));
        }
        bf.Serialize(file, data);
        file.Close();
    }
    public void Load()
    {

        if (File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
        {
            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
            data = (InfoSave)bf.Deserialize(file);
            file.Close();

            for(int i = 0; i<data.list.Count;i++){
                Logger.LogFormat("[Load] Value : {0}",data.list[i]);
            }
        }
    }

    public InfoSave GetData(){
        return this.data;
    }
    #endregion

}

Binary형태로 file을 Serialize(동기화)시켜서 데이터를 쓰고, Deserialize를 통해서 데이터를 읽어드리면 저장된 데이터를 그대로 읽을 수 있다.

 

참고 [BinaryFormatter.Serialize]

참고 :  [BinaryFormatter.Deserialize]

 

 ★

 

반응형

댓글