그림에서

name

min_damage

max_damage

item_type

4가지 속성을 가지고 배열을 만들어서 json 파일로저장

 

json파일을 만들때 " "가 중요하다.

 

만들고 나서 Format을 누르면 잘 작성이 됬는지 확인할 수 있다

코드를 작성 후 오류가 나지 않으면 이렇게 생성 된 걸 알 수 있다.

 

그 후 Text를 복사하고 메모장에 저장

저장할 때 주의

 

우선 Unity에 Resources 라는 폴더를 만들고 넣어주면 되는데 이 때 반드시 폴더명을 이렇게 해주어야 한다.

https://www.newtonsoft.com/json

 

Json.NET - Newtonsoft

× PM> Install-Package Newtonsoft.Json or Install via VS Package Management window. ZIP file containing Json.NET assemblies and source code: Json.NET

www.newtonsoft.com

Newtonsoft.Json은 C#에서 JSON 데이터를 처리하는 데 사용되는 강력한 라이브러. 주요 기능은 다음과 같다.

  1. JSON 직렬화(Serialization): C# 객체를 JSON 문자열로 변환합니다.
  2. JSON 역직렬화(Deserialization): JSON 문자열을 C# 객체로 변환합니다.
  3. LINQ를 사용한 JSON 쿼리(Query): LINQ 쿼리를 사용하여 JSON 데이터를 쉽게 쿼리하고 필터링할 수 있습니다.
  4. JSON 스키마(Validation): JSON 데이터가 주어진 스키마에 부합하는지 확인할 수 있습니다.
  5. JSON 파싱(Parsing): JSON 문자열을 해석하고 객체로 변환합니다.
  6. JSON 변환(Transform): JSON 데이터를 다른 형식으로 변환합니다.
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public class HelmMain : MonoBehaviour
{
    
    void Start()
    {
        TextAsset asset = Resources.Load<TextAsset>("helm_data");
        string json = asset.text;
        Debug.Log(json);

        HelmData data = JsonConvert.DeserializeObject<HelmData>(json);
        //Debug.Log(data);  
        Debug.LogFormat("{0} {1} {2} {3}", data.name, data.min_damage, data.max_damage, data.item_type);

        //저장
        //직렬화 객체 생성
        HelmInfo info = new HelmInfo(data.min_damage, data.max_damage);
        //직렬화 시작(객체 ->문자열)
        string serializedJson = JsonConvert.SerializeObject(info);

        //파일로 저장
        //Application.persistentDataPath : 플랫폼 OS에 따라 경로를 자동으로 잡아줌
        string path = Application.persistentDataPath + "/helm_info.json";
        Debug.Log(path);
        //문자열을 파일로 저장
        File.WriteAllText(path, serializedJson); //경로, 문자열
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelmData
{
    public string name;
    public int min_damage;
    public int max_damage;
    public string item_type;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HelmInfo
{
    public int min_damage;
    public int max_damage;

    public HelmInfo(int min_damage, int max_damage)
    {
        this.min_damage = min_damage;
        this.max_damage = max_damage;
    }
}

실행을 시켜보면

1. 데이터를 문자열을 출력

2. 데이터를 역직렬화 후 데이터를 잘 받고 있는지 확인

3. Helminfo클래스를 메인에서 불러온 후 생성자를 생성한뒤 지정한 경로 위치로 생성후 저장 => 그 위치 출력

 

보기와 같이 출력한 경로를 검색하면 지정된 경로에 파일이 저장됨을 확인 할 수 있다.

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을 다시 만들어서 실행해 보아야겠다.

 

 

 

가이드 화면을 좌측 정렬

 

Content  -> shift + alt + 왼쪽 상단

 

Content Size Fitter 컴포넌트 추가

 

그 후 컨텐트 안에 있는 이미지 컴포넌트를 만든 후 복사

 

그후 Spacing을 조절하면 복사된 이미지들이 공간이 생긴다.

 

ScrollView를 클릭후 Scroll Rect 를 생성하고

ScrollView를 할당시킨다음

Vertical를 체크해제 하면 된다.

+ Recent posts