2025유니티수업

0626 깃허브 , 데이터 저장/불러오기

버스창문 2025. 6. 26. 18:58

GitIgnore

유니티 기준 프로젝트 파일에 직접 넣어야함

진짜 파일 올라가는 숫자 확줄음 지림 개사기임

 

 

 

_________________________________________________________

데이터를 저장하는 방식

1. 파일에 기록 방식 -> 싱글 게임 같은 경우 하드에 저장시킴

2. 별도의 데이터베이스 서버에  원격으로 저장 

 

void LoadGameData()
{
    KillCnt = PlayerPrefs.GetInt("KillCnt", 0);//PlayerPrefs : 플레이어 Preferences
    this.killCntTxtUi.text = $"Kill : <color=#ff0000>{this.KillCnt.ToString("000")}</color>";
}

PlayerPrefs : 유니티에서 자체적으로 지원하는 데이터 저장용 클래스

key : dictionary형식으로 저 키 안에 값이 있으면 그거 가져옴

defaultValue : 값이 없으면 저거로 넣음

public void IncKillCnt()
{
    //++KillCnt;
    PlayerPrefs.SetInt("KillCnt", ++this.KillCnt);
    this.killCntTxtUi.text = $"Kill : <color=#ff0000>{this.KillCnt.ToString("000")}</color>";
}

 

껐다켜도 유지됨

 

PlayerPrefs

DeleteAll : 모든 키값 삭제

DeleteKey : 특정 키값 삭제

Get~~/Set~~ : 가져오기 저장하기

Hashkey : 해당키가 존재하는지 여부 반환

Save : 키값 물리적으로 하드에 저장

 

 

PlayerPrefs의 문제점 : 보안이 전혀 안됨, 저장경로에 .plist 파일에 전부 그냥 들어가있음

비밀번호 같은걸 저장하면 다 털림

 

 

 

바이너리 파일 저장 : byte로 저장

int float string등의 데이터를 byte로 직렬화(serialization)

거꾸로 byte를 다시 int등으로 바꾸는건 역직렬화(DeSerialization)

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DataInfo
{
    [System.Serializable]
    public class GameData
    {
        public int killCnt = 0;
        public float hp = 120f;
        public float damage = 25;
        public float speed = 6;
    }
    [System.Serializable]
    public class Item
    {
        public enum ItemType
        {
            HP, Speed, Shock, Granade
        }
        public enum ItemCalc
        {
            Value, Persent
        }
        public ItemType type;
        public ItemCalc calc;
        public string name;
        public string desc;
        public float value;
    }
}

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DataInfo; // 만들어둔 GameData를 사용하기 위한 namespace사용 선언

public class ItemInfo : MonoBehaviour
{
    public Item itemData;
}

 

이걸 부착해서 사용

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO; // 파일 입출력을 위한 네임 스페이스
using System.Runtime.Serialization.Formatters.Binary; // 실시간에서 직렬화 바이너리 파일 형식을 위한 네임 스페이스
using DataInfo;
using UnityEngine.UI;

public class DataManager : MonoBehaviour
{
    [SerializeField] private string dataPath; //파일이 저장될 물리적인 경로
    public void Initialize()
    {
        dataPath = Application.persistentDataPath + "/gameData.dat";
    }
    public void Save(GameData data)
    {
        BinaryFormatter bf = new BinaryFormatter(); // 직렬화 해주는애 선언
        FileStream file = File.Create(dataPath); // 파일 스트림 경로 잡아두기
        bf.Serialize(file, data); // 직렬화
        file.Close(); // 경로 다시 닫기
    }
    public GameData Load()
    {
        if (File.Exists(dataPath)) //만약 저장 파일이 존재한다면
        {
            BinaryFormatter bf =new BinaryFormatter();
            FileStream file = File.Open(dataPath, FileMode.Open);
            GameData data = (GameData)bf.Deserialize(file); // 직렬화 됐던걸 다시 역직렬화
            file.Close();
            return data;
        }
        return new GameData();//만약 파일이 없다면 새거 생성해서 넣음
    }
}

 

persistentDataPath : 파일을 읽고 쓸수 있는 저장 경로 반환

모바일에선 공용폴더의 경로로 반환되고, 앱이 업그레이드 되어도 파일은 유지

 

        this.max_Hp = (int)GameManager.Instance.gameData.hp;
        this.hp = this.max_Hp;
        this.moveSpeed = GameManager.Instance.gameData.speed;

Ctrl등에서 hp잡던걸 gameData에서 받아오게 바꿈

private void OnApplicationQuit()
{
    this.dataManager.Save(this.gameData);
}

게임 끌때 저장

private void Awake()
{
    Instance = this;
    this.dataManager = this.GetComponent<DataManager>();
    //this.dataManager = new DataManager();
    dataManager.Initialize();
    LoadGameData(); //세이브된 데이터 파일을 로드(불러오기)
}

void Start()
{
    //OnInventory(false);
}
void LoadGameData()
{
    //KillCnt = PlayerPrefs.GetInt("KillCnt", 0);//PlayerPrefs : 플레이어 Preferences
    gameData = this.dataManager.Load();
    this.killCntTxtUi.text = $"Kill : <color=#ff0000>{this.gameData.killCnt.ToString("000")}</color>";
}

게임 킬때 gameData에 Load해서 넣음

 

 

Drop(장비창) -> 자신이 가지고있는 장비, 이 효과를 적용할 플레이어

Drag(장비) -> 지가 올리는 스텟

장비창에 장비를 올려두면 Drop이 장비 정보를 갖게되고, 
그 장비의 효과를 플레이어한태 적용
빼면 Drop이 가지고있던 장비가 사라지고, 효과 또한 제거

player(유저) -> 장비창 data 를 가지고있어야함, 한두개가 아닐테니, 그 리스트를 data로써
가지고 있으면 됨
기초 스탯 Data도 가지고 있어야함
그 후 기초스탯, 장비창 변동 내용만 들고있으면 게임 부팅시 알아서 적용되는 형태

DataManager -> Player가 본인의 data를 Save하거나
게임을 킬때 Load하는 기능만 있어도 됨