아카이브

[VR 팀프로젝트] UI에 UpgradeData 데이터 넣기 본문

VR 콘텐츠 제작

[VR 팀프로젝트] UI에 UpgradeData 데이터 넣기

timbercat 2023. 11. 29. 18:18

업그레이드 데이터 엑셀파일로 정리 후 제이슨 변환

https://shancarter.github.io/mr-data-converter/

 

Mr. Data Converter

 

shancarter.github.io

 

https://jsonviewer.stack.hu/

 

Online JSON Viewer and Formatter

 

jsonviewer.stack.hu

 

Asset/Data 안에 넣어줌

UpgradeData 스크립트 생성

 

DataManager.cs를 만들어 json파일을 역직렬화 하고 사전에 저장

 

main 스크립트 생성 후 버튼을 누르면 각각의 데이터를 콘솔 창에 나타나게 함

 

 

UpgradeData.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SYJ
{
    public class UpgradeData
    {
        public int id;
        public string name;
        public string desc;
    }
}

 

DataManager.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.IO;
using System.Linq;

namespace SYJ
{
    public class DataManager : MonoBehaviour
    {
        public static readonly DataManager Instance = new DataManager();
        private Dictionary<int, UpgradeData> dicUpgradeDatas;

        public void LoadUpgradeData()
        {
            TextAsset asset = Resources.Load<TextAsset>("Data/upgrade_data");
            //json 문자열 가져오기 
            string json = asset.text;
            Debug.Log(json);
            //역직렬화 
            UpgradeData[] arrUpgradeDatas = JsonConvert.DeserializeObject<UpgradeData[]>(json);
            Debug.LogFormat("upgradeDatas.Length: {0}", arrUpgradeDatas.Length);

            //사전에 넣기
            this.dicUpgradeDatas = arrUpgradeDatas.ToDictionary(x => x.id); //배열에 있는 요소로 새로운 사전을 만듬 
            Debug.LogFormat("this.dicUpgradeDatas.Count: {0}", this.dicUpgradeDatas.Count);
        }

        public List<UpgradeData> GetUpgradeDatas()
        {
            return this.dicUpgradeDatas.Values.ToList();
        }
    }
}

 

TestUIMain.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace SYJ
{
    public class TestUIMain : MonoBehaviour
    {
        [SerializeField] private Button[] upgradebtn;
        
        void Start()
        {
            DataManager.Instance.LoadUpgradeData();
            List<UpgradeData> upgradeData = DataManager.Instance.GetUpgradeDatas();
            
            for(int i = 0; i < upgradebtn.Length; i++) 
            {
                int index = i;
                upgradebtn[index].onClick.AddListener(() => 
                {
                    Debug.Log(upgradeData[index].name);
                    Debug.Log(upgradeData[index].desc);
                });
            }
        }
    }
}