산대특/게임 UIUX 프로그래밍
데이터 연동해서 UI 보여주기
꽂무남
2024. 2. 13. 23:37
jsonviewer 사이트를 이용해서 json을 작성 후 format 누르면 제대로 만들어졌는지 유효성 확인이 된다.
그럼 메모장에 복사 후 이와 같이 저장한 다음 만들어둔 Resources 폴더로 저장
주의점 : 폴더명은 Resources여야 한다.
빈오브젝트 생성 후 스크립트 할당
json이 유니티에 들어갈 때 텍스트에셋으로 바뀜을 확인할 수 있다.
텍스트에셋이 잘 받아졌는지 확인
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft;
using Newtonsoft.Json;
public class Test6Main : MonoBehaviour
{
void Start()
{
TextAsset asset = Resources.Load<TextAsset>("nation_data");
Debug.Log(asset);
}
}
역직렬할 매핑클래스 생성
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NationData
{
public string nation;
public int population;
public string religion;
}
중요한 것은 여기는 비모노이기에 상속받는 : Monobehaviour를 제거
이제 역직렬화를 해주고 출력되는지 확인할 것이다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft;
using Newtonsoft.Json;
public class Test6Main : MonoBehaviour
{
void Start()
{
TextAsset asset = Resources.Load<TextAsset>("nation_data");
//Debug.Log(asset);
string json = asset.text;
Debug.Log(json);
//역직렬화
NationData data = JsonConvert.DeserializeObject<NationData>(json);
Debug.LogFormat("nation : {0}", data.nation);
Debug.LogFormat("population : {0}", data.population);
Debug.LogFormat("religion : {0}", data.religion);
}
}
아틀라스를 만들어서 국기들을 넣어준다.
하다가 무언가 잘못됨을 느꼈다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.U2D;
public class NationDataCellView : MonoBehaviour
{
[SerializeField] private SpriteAtlas atlas;
[SerializeField] private Image nation;
[SerializeField] private TMP_Text populationText;
[SerializeField] private TMP_Text religionText;
public void Init(NationData data)
{
this.nation.sprite = atlas.GetSprite(data.nation);
this.populationText.text = string.Format("{0}", data.population);
this.religionText.text = data.religion;
}
}
Atlas를 사용하여
this.imgIcon.sprite = atlas.GetSprite(data.icon);
이런식으로 이미지를 할당해주어야 하는데
json파일에 이미지를 넣을 공간을 만들지 않았다는 것이다.
json을 다시 만들어서 실행해 보아야겠다.