정적 스크롤뷰 먼저 만들고 이어서 진행
좌우로 넘기는 정적 스크롤뷰 만들기
정적 스크롤뷰 만들기 1. Image scrollview 스크롤할 영역만큼 크기 조절 2. scrollview 안에 Create Empty contents 앵커 왼쪽 위, 사이즈 조절 Add Component Content Size Fitter-Horizontal Fit-Preferred Size Add Component Horizonta
s00wb.tistory.com
**변하지 않는 데이터(~data)만 연동해서 만드는 경우
ShopMain
1. CreateEmpty ShopMain+ShopMain(Script)
4. UIShop 관리
10. UIShop 초기화
재화, 탭 메뉴, 스크롤 뷰 등
15. LoadData
19-2. EventManager에게서 이벤트 전달 받음
19-3. 이벤트에 메서드 연결
btnAd 클릭-광고 보여주기
btnPurchase 클릭-id에 따라 이름, 가격 출력
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShopMain : MonoBehaviour
{
//4
public UIShop uiShop;
void Start()
{
//15
DataManager.instance.LoadData(); //데이터 로드
//19-2, 19-3
EventManager.instance.onBtnAdClick = () => {
Debug.Log("광고를 보여줍니다.");
};
EventManager.instance.onPurchaseChest = (id) => {
var data = DataManager.instance.GetData(id);
Debug.LogFormat("{0}, {1}, {2}", data.id, data.name, data.price);
};
//10
this.uiShop.Init(); //UI Shop을 초기화
}
}
UIShop
2. Canvas 이름을 UIShop으로 변경+UIShop(Script)
5. UIScrollView 관리
11. UIScrollView 초기화
12. SpriteAtlas 관리
UIScrollView에서만 아틀라스 사용->UIShop에서 아틀라스 관리
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class UIShop : MonoBehaviour
{
//5
public UIScrollView uiScrollView;
//12
public SpriteAtlas atlas;
public void Init()
{
//11
this.uiScrollView.Init();
}
}
UIScrollView
3. scrollview 이름을 UIScrollView로 변경+UIScrollView(Script)
6. 아이템 생성할 위치 알기(contents)
9. AddItem/AddItemAD 메서드
contents 받아서 그 자식으로 아이템 객체 생성
17-2. item 생성 시 data 매개변수로 전달받아 item 초기화
생성한 아이템 객체의 itemGem/itemAD 버튼 클릭 이벤트에 메서드 연결
17. GetShopDatas(List 반환)
17-1. 리스트에서 data 받아서 data.type에 따라 item 생성 메서드 결정
19-1. ad/purchase 버튼 클릭 이벤트 발생하면 EventManager에 전달해야 함
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIScrollView : MonoBehaviour
{
//6
public Transform contentTrans;
public GameObject itemADPrefab;
public GameObject itemPrefab;
public void Init()
{
//17
List<ShopData> list = DataManager.instance.GetShopDatas();
//17-1
foreach (ShopData data in list)
{
if (data.type == 0)
{
//normal
this.AddItem(data);
}
else if (data.type == 1)
{
//ad
this.AddItemAD(data);
}
}
}
//9
public void AddItemAD(ShopData data)
{
var go = Instantiate(this.itemADPrefab, this.contentTrans);
UIScrollViewItemAD itemAD = go.GetComponent<UIScrollViewItemAD>();
//17-2
itemAD.Init(data);
itemAD.btnAD.onClick.AddListener(() => {
Debug.LogFormat("[show ad] id: {0}", itemAD.id);
//19-1 사건의 발생
EventManager.instance.onBtnAdClick();
});
itemAD.btnGem.onClick.AddListener(() => {
Debug.LogFormat("[AD] purchase chest : id : {0}", itemAD.id);
//19-1
EventManager.instance.onPurchaseChest(itemAD.id);
});
}
//9
public void AddItem(ShopData data)
{
var go = Instantiate(this.itemPrefab, this.contentTrans);
UIScrollViewItem item = go.GetComponent<UIScrollViewItem>();
//17-2
item.Init(data);
item.btnGem.onClick.AddListener(() => {
Debug.LogFormat("purchase chest : id: {0}", item.id);
//19-1
EventManager.instance.onPurchaseChest(item.id);
});
}
}
UIScrollViewItem
7. item 이름을 UIScrollVIewItem(기본형)으로 변경+UIScrollViewItem(Script)
8. item 안의 요소들 멤버변수로 정의
txtName, imgChest, btnGem, txtPrice
18. ShopData 매개변수로 받아서 item 멤버변수 값 초기화
id, txtName, imgChest(AtlasManager 이용), txtPrice 등 (버튼x)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class UIScrollViewItem : MonoBehaviour
{
//8
public TMP_Text txtName;
public Image imgChest;
public Button btnGem;
public TMP_Text txtPrice;
public int id;
//18
public void Init(ShopData data)
{
this.id = data.id;
this.txtName.text = data.name;
var atlas = AtlasManager.instance.GetAtlasByName("UIShop");
this.imgChest.sprite = atlas.GetSprite(data.sprite_name);
this.imgChest.SetNativeSize();
//한 개만 사이즈 조절해보기
if (data.type == 1) //AD
{
//300, 277
this.imgChest.GetComponent<RectTransform>().sizeDelta = new Vector2(300, 277);
}
this.txtPrice.text = string.Format("{0:#,0}", data.price);
}
}
UIScrollViewItemAD
7-1. UIScrollVIewItemAD+UIScrollViewItem(Script)
8-1. UIScrollVIewItem과 다른 요소 멤버변수로 정의
btnAD
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//7-1, 8-1
public class UIScrollViewItemAD : UIScrollViewItem
{
public Button btnAD;
}
13. Resources 폴더(이름 정해져 있음)-Data 폴더-shop_data(json 파일) 넣기
ShopData
13-1. shop_data 매핑(바인딩) 클래스
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//13-1 바인딩 클래스
public class ShopData
{
public int id;
public string name;
public string sprite_name;
public int price;
public int type;
//생성자 필요 없다
}
DataManager(MonoBehaviour x)
14. LoadData 메서드
shop_data(json) 파일 로드해서 json변수에 담기
json 변수 값 역직렬화해서 배열로 만들기
배열->딕셔너리
16. GetShopDatas 메서드
딕셔너리의 values(ShopData)로 리스트 만들어서 리스트 반환
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.Linq;
public class DataManager
{
public static readonly DataManager instance = new DataManager();
//컬렉션 초기화 (링큐 사용 안할때)
private Dictionary<int, ShopData> dicShopData;// = new Dictionary<int, ShopData>();
//생성자
private DataManager() { }
public ShopData GetData(int id)
{
return this.dicShopData[id];
}
public void LoadData()
{
//TextAsset을 로드
TextAsset asset = Resources.Load<TextAsset>("Data/shop_data"); //경로를 포함한 확장자를 뺀 이름
//asset의 문자열
var json = asset.text;
Debug.Log(json);
//역직렬화
ShopData[] arrShopDatas = JsonConvert.DeserializeObject<ShopData[]>(json);
this.dicShopData = arrShopDatas.ToDictionary(x => x.id); //새로운 사전 객체가 생성 반환
//링큐 사용 안 할 때
//foreach (var data in arrShopDatas) {
// this.dicShopData.Add(data.id, data);
//}
Debug.LogFormat("shop data loaded : {0}", this.dicShopData.Count); //5
}
public List<ShopData> GetShopDatas()
{
return this.dicShopData.Values.ToList();
}
}
AtlasManager(MonoBehaviour o)
18-1. SpriteAtlas 배열 관리
아틀라스 이름을 key, 아틀라스를 value로 하는 딕셔너리 생성
18-2. GetAtlasByName 메서드
아틀라스 이름으로 아틀라스를 찾아서 반환
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class AtlasManager : MonoBehaviour
{
public static AtlasManager instance;
//18-1
public SpriteAtlas[] arrAtlas;
public Dictionary<string, SpriteAtlas> dicAtlas = new Dictionary<string, SpriteAtlas>();
private void Awake()
{
AtlasManager.instance = this;
Debug.LogFormat("this.arrAtlas.Length: {0}", this.arrAtlas.Length);
for (int i = 0; i < this.arrAtlas.Length; i++)
{
var atlas = this.arrAtlas[i];
//이름Atlas
var atlasName = atlas.name.Replace("Atlas", "");
this.dicAtlas.Add(atlasName, atlas);
}
}
//18-2
public SpriteAtlas GetAtlasByName(string name) //key
{
if (this.dicAtlas.ContainsKey(name))
{
return this.dicAtlas[name];
}
else
{
Debug.LogFormat("<color=red>key: {0}를 찾을수 없습니다.</color>", name);
return null;
}
}
}
EventManager(MonoBehaviour x)
19. 이벤트 발생 전달
ad/purchase 버튼 클릭 이벤트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EventManager
{
public static readonly EventManager instance = new EventManager();
//19
public System.Action onBtnAdClick;
public System.Action<int> onPurchaseChest;
private EventManager() { }
}
실행 결과
스크롤도 잘 넘어가고 버튼 클릭도 잘 된다
'Unity > UI' 카테고리의 다른 글
uGUI 세팅 팝업 만들기 (0) | 2023.02.20 |
---|---|
상점 동적 스크롤뷰/데이터 연동/Tab 메뉴 구현 (0) | 2023.02.19 |
좌우로 넘기는 정적 스크롤뷰 만들기 (0) | 2023.02.13 |
슬라이더 만들기 (0) | 2023.02.11 |
체크박스 만들기 (0) | 2023.02.07 |