0421 데이터 저장 및 로딩

2021. 4. 21. 18:28unity

Application.persistentDataPath

지속되는(persistent) 데이터 디렉토리로의 경로(읽기전용)
실행중에 데이터가 보호되어야 할 때 저장될 수 있는 디렉토리 값

보호되어야 하는 데이터이므로 C드라이브의 유저>숨겨진 폴더 항목 중 appData 폴더에 저장된다.
폴더명은 File>Build Settings>Player>Company Name/Product Name으로 설정 가능

using UnityEngine;

public class GameInfo 
{
    public List<StageInfo> stageInfos;

    public GameInfo() 
    {
        this.stageInfos = new List<StageInfo>();
    }
}
using UnityEngine;

public class StageInfo 
{
    public int stageNum;
    public int state;
    public int stars;

    //생성자
    public StageInfo(int stageNum, int state = 2, int stars=0) 
    {
        this.stageNum = stageNum;
        this.state = state;
        this.stars = stars;
		//저장되는 데이터 종류들
    }
}
using System.IO;
using UnityEngine;
using UnityEngine.UI;

public class SaveTest : MonoBehaviour
{
    public Button btnSave;
    public Button btnLoad;
    public GameInfo gameInfo;
    private int maxStage=72;

    private void Start()
    {
        var path = string.Format("{0}/game_info.json", Application.persistentDataPath);

        if (File.Exists(path))
        {
            //기존 유저 
            var json = File.ReadAllText(path);
            Debug.Log(json);
            this.gameInfo = JsonConvert.DeserializeObject<GameInfo>(json);
            Debug.Log("loaded success");
        }
        else
        {
            //신규 유저 
            //초기화 
            this.gameInfo = new GameInfo();
            for (int i = 0; i < this.maxStage; i++)
            {
                var state = 2;
                if (i == 0)
                {
                    state = 1;
                }
                var stageInfo = new StageInfo(i + 1, state);
                this.gameInfo.stageInfos.Add(stageInfo);
            }
            var json = JsonConvert.SerializeObject(this.gameInfo);
            Debug.Log(json);
            File.WriteAllText(path, json);
            Debug.Log("saved success");
        }

        this.btnSave.onClick.AddListener(() => {
            Debug.Log("save");
            Debug.LogFormat("dataPath: {0}", Application.dataPath);
            Debug.LogFormat("persistentDataPath: {0}", Application.persistentDataPath);
        });
        this.btnLoad.onClick.AddListener(() => {
            Debug.Log("load");
        });
    }
}

 


Stage_Data

id

stage_no

name

reward_id

int

int

string

int

1000

1

Stage A

10000

1001

2

Stage B

10001

 

using UnityEngine;

public class StageData 
{
    public int id;
    public int stage_no;
    public string name;
    public int reward_id;
}

Reward_Data

id

item_0_id

item_0_amount

item_1_id

item_1_amount

item_2_id

item_2_amount

int

int

int

int

int

int

int

10000

100

1

101

2

100

1

10001

101

1

105

3

103

2

public class RewardData 
{
    public int id;
    public int item_0_id;
    public int item_0_amount;

    public int item_1_id;
    public int item_1_amount;

    public int item_2_id;
    public int item_2_amount;

}

Item_Data

id

name

sprite_name

desc

int

string

string

string

100

빨간물약

stage_ready_item_potion_red

체력을 회복해줍니다.

101

stage_ready_item_sword_A

공격력이 3입니다.

102

타이머

stage_ready_item_timer

시간을 추가합니다

using UnityEngine;

public class ItemData
{
    public int id;
    public string name;
    public string sprite_name;
    public string desc;
}

 

 

using UnityEngine;
using UnityEngine.U2D;

public class TestStage : MonoBehaviour
{
    public TestUIStageItem item;
    public UIStageReady uiStageReady;
    public SpriteAtlas atlas;

    void Start()
    {
        DataManager.GetInstance().LoadDatas();
        item.Init();
        item.btn.onClick.AddListener(() =>
        {
            var stageData = DataManager.GetInstance().dicStageDatas[item.id];
            Debug.LogFormat("{0} {1}", stageData.stage_no, stageData.reward_id);

            var rewardData = DataManager.GetInstance().dicRewardDatas[stageData.reward_id];
            var item0Data = DataManager.GetInstance().dicItemDatas[rewardData.item_0_id];
            var item1Data = DataManager.GetInstance().dicItemDatas[rewardData.item_1_id];
            var item2Data = DataManager.GetInstance().dicItemDatas[rewardData.item_2_id];

            Debug.LogFormat("{0}{1}{2}{3}", item0Data.id, item0Data.name, item0Data.sprite_name, item0Data.desc);
            Debug.LogFormat("{0}{1}{2}{3}", item1Data.id, item1Data.name, item1Data.sprite_name, item1Data.desc);
            Debug.LogFormat("{0}{1}{2}{3}", item2Data.id, item2Data.name, item2Data.sprite_name, item2Data.desc);
        });
    }
using UnityEngine;
using UnityEngine.UI;

public class TestUIStageItem : MonoBehaviour
{
    public int id;
    public Text txtStageNo;
    public Button btn;

    public void Init()
    {
        var data = DataManager.GetInstance().dicStageDatas[this.id];
        this.txtStageNo.text = data.stage_no.ToString();
    }
}
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.Linq;
public class DataManager
{
    private static DataManager instance;
    public Dictionary<int, StageData> dicStageDatas;
    public Dictionary<int, RewardData> dicRewardDatas;
    public Dictionary<int, ItemData> dicItemDatas;

    //생성자 
    private DataManager()
    {

    }

    public static DataManager GetInstance()
    {
        if (DataManager.instance == null)
        {
            DataManager.instance = new DataManager();
        }
        return DataManager.instance;
    }
    public void LoadDatas()
    {
        var ta = Resources.Load<TextAsset>("stage_data");
        var json = ta.text;
        this.dicStageDatas = JsonConvert.DeserializeObject<StageData[]>(json).ToDictionary(x => x.id);

        ta = Resources.Load<TextAsset>("reward_data");
        json = ta.text;
        this.dicRewardDatas = JsonConvert.DeserializeObject<RewardData[]>(json).ToDictionary(x => x.id);

        ta = Resources.Load<TextAsset>("item_data");
        json = ta.text;
        this.dicItemDatas = JsonConvert.DeserializeObject<ItemData[]>(json).ToDictionary(x => x.id);

        Debug.LogFormat("load completed!, {0}, {1}, {2}", this.dicStageDatas.Count, this.dicRewardDatas.Count, this.dicItemDatas.Count);
    }
}

'unity' 카테고리의 다른 글

0423 ugui scroll view 3D+데이터 테이블 연동2 (RayCast Target)  (0) 2021.04.23
0423 ui scroll view+데이터 테이블 연동  (0) 2021.04.23
0421 UI Stage  (0) 2021.04.21
0420 Item Pick up+인벤토리 연동  (0) 2021.04.20
0420 UI Inventory  (0) 2021.04.20