유니티 심화/복습

[복습] LearnUGUI - Practice05 [Shop], DataManager로 데이터 받아오기

다모아 2023. 9. 8. 02:28

너무 이해가 안되서 천천히 생각하면서 계속 반복반복했다.

처음에는 UIChestScrollView가 무슨 역할인지도 이해가 안됐는데 그나마 이해가 되고

DataManager- LoadChestData함수의 역직렬화도 GetChestData의 ToList로 데이터를 return 하는 것도 보다보니 익숙해진다.

그래도 이해가 잘 되진 않아서 계속 연습해야할 것 같다.

특히 AtlasManager는 다른 것도 벅찬데 이것도 이해하려면 잘 모르겠어서 그냥 적고 패스했다..

 


Chest_data.xlsx
0.01MB
Chest_data.json
0.00MB

6. DataManager로 데이터 받아오기


Practice05UIChestCell

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

namespace Practice05
{
    public class Practice05UIChestCell : MonoBehaviour
    {
        public enum eChestType
        {
            Wooden, Silver, Golden, Epic, Legendary
        }

        [SerializeField]
        private eChestType chestType;

        public eChestType ChestType
        {
            get
            {
                return this.chestType;
            }
        }

        [SerializeField]
        private int price;

        [SerializeField]
        private TMP_Text txtPrice;
        [SerializeField]
        private TMP_Text txtName;
        [SerializeField]
        private Image icon;

        protected int Price => this.price;

        [SerializeField]
        protected Button btnPrice;

        public Action onClickPrice;
        public virtual void Init(Practice05ChestData data)
        {
            this.price = data.price;
            this.txtName.text = data.name;
            this.txtPrice.text = this.price.ToString();
            this.chestType = (eChestType)data.type;

            //찾아오기
            SpriteAtlas atlas = Practice05AtlasManager.instance.GetAtlas("UIAtlas");
            //스프라이트 이름 받아와서 넣기
            this.icon.sprite = atlas.GetSprite(data.sprite_name);
            this.icon.SetNativeSize();

            this.btnPrice.onClick.AddListener(() =>
            {
                Debug.LogFormat("{0}, {1}", this.chestType, this.Price);
                this.onClickPrice();
            });
        }
    }
}

 

Practice05UIChestCellAd

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

namespace Practice05
{
    public class Practice05UIChestCellAd : Practice05UIChestCell
    {
        [SerializeField]
        private Button btnAd;

        public Action onClickAd;
        public override void Init(Practice05ChestData data)
        {
            //부모꺼 사용
            base.Init(data);

            this.btnAd.onClick.AddListener(() =>
            {
                Debug.LogFormat("{0}, 광고보기", this.ChestType);
                this.onClickAd();
            });
        }
    }
}

 

Practice05UIChestScrollView

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

namespace Practice05
{
    public class Practice05UIChestScrollView : MonoBehaviour
    {
        [SerializeField]
        private GameObject uiChestCellPrefab;
        [SerializeField]
        private GameObject uiChestCellAdPrefab;
        [SerializeField]
        private Transform contentTr;

        private List<Practice05UIChestCell> cellList = new List<Practice05UIChestCell>();

        public void Init()
        {
            List<Practice05ChestData> chestDatas = Practice05DataManager.instance.GetChestDataList();
            foreach(Practice05ChestData chestData in chestDatas)
            {
                //우드인지 확인 아닌지 확인
                Practice05UIChestCell cell = null;

                if((Practice05UIChestCell.eChestType)chestData.type == Practice05UIChestCell.eChestType.Wooden)
                {
                    //우드라면 Ad지
                    //프리팹 해줘야지
                    GameObject go = Instantiate<GameObject>(this.uiChestCellAdPrefab, this.contentTr);
                    //컴포넌트 할당해주고
                    cell = go.GetComponent<Practice05UIChestCell>();
                    //cell을 cellAd로 바꿔주고
                    Practice05UIChestCellAd cellAd = cell as Practice05UIChestCellAd;

                    cellAd.onClickAd = () => {
                        Debug.LogFormat("{0}, 광고보기", chestData.name);
                    };

                    cellAd.onClickPrice = () => {
                        Debug.LogFormat("{0}, {1}", chestData.name, chestData.price);
                    };
                }
                else
                {
                    //우드가 아니라면
                    //프리팹 해주고
                    GameObject go = Instantiate<GameObject>(this.uiChestCellPrefab, this.contentTr);
                    //컴포넌트 할당!
                    cell = go.GetComponent<Practice05UIChestCell>();
                    //대리자 소환
                    cell.onClickPrice = () => {
                        Debug.LogFormat("{0}, {1}", chestData.name, chestData.price);
                    };
                }
                //UiChestCell Init
                cell.Init(chestData);
                //리스트에 저장 ?
                this.cellList.Add(cell);
            }
        }
    }
}

 

Practice05DataManager

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

namespace Practice05
{
    public class Practice05DataManager
    {
        public static readonly Practice05DataManager instance = new Practice05DataManager();

        private Dictionary<int, Practice05ChestData> dicChestDatas = new Dictionary<int, Practice05ChestData>();

        public void LoadChestData()
        {
            TextAsset asset = Resources.Load<TextAsset>("Chest_Data");
            string json = asset.text;
            //역직렬화
            Practice05ChestData[] datas = JsonConvert.DeserializeObject<Practice05ChestData[]>(json);
            foreach (Practice05ChestData data in datas)
            {
                Debug.LogFormat("{0}, {1}, {2}, {3}, {4}", data.id, data.name, data.type, data.price, data.sprite_name);
                //저장할 변수 가져와
                this.dicChestDatas.Add(data.id, data);
            }
            Debug.LogFormat("{0}개의 DataManager 로드 완료!", this.dicChestDatas.Count);
        }

        public List<Practice05ChestData> GetChestDataList()
        {
            return this.dicChestDatas.Values.ToList();
        }
    }
}

 

Practice05AtlasManager

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

namespace Practice05
{
    public class Practice05AtlasManager : MonoBehaviour
    {
        public static Practice05AtlasManager instance;
        //받아올 이름 적기
        [SerializeField]
        private string[] arrAtlasNames;

        private Dictionary<string, SpriteAtlas> dicAtlases = new Dictionary<string, SpriteAtlas>();

        private void Awake()
        {
            if(instance != null && instance != this)
            {
                Destroy(this);
                throw new System.Exception("An instance of this singleton already exists.");
            }
            else
            {
                instance = this;
            }

            DontDestroyOnLoad(this.gameObject);
        }

        public void LoadAtlases()
        {
            foreach(string atlasName in this.arrAtlasNames)
            {
                SpriteAtlas atlas = Resources.Load<SpriteAtlas>(atlasName);
                this.dicAtlases.Add(atlasName, atlas);
            }

            Debug.LogFormat("{0}개의 아틀라스를 로드했습니다.", this.dicAtlases.Count);
        }

        public SpriteAtlas GetAtlas(string atlasName)
        {
            return this.dicAtlases[atlasName];
        }
    }
}

 

Practice05ChestData

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

namespace Practice05
{
    public class Practice05ChestData
    {
        public int id;
        public string name;
        public int type;
        public int price;
        public string sprite_name;
    }
}

 

Practice05UIMain

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

namespace Practice05
{
    public class Practice05UIMain : MonoBehaviour
    {
        [SerializeField]
        private Practice05UIChestScrollView uIChestScrollView;

        // Start is called before the first frame update
        void Start()
        {
            Practice05DataManager.instance.LoadChestData();
            Practice05AtlasManager.instance.LoadAtlases();
            this.uIChestScrollView.Init();
        }
    }
}