기본 사용법(유니티 기능)
{
"stats": [
{
"level": "1",
"hp": "100",
"attack": "10"
},
{
"level": "2",
"hp": "150",
"attack": "15"
},
{
"level": "3",
"hp": "200",
"attack": "20"
}
]
}
위와 같은 내용을 지닌 Json을 가지고 예시를 들겠습니다. (파일 경로: Data/StatData )
[Serializable]
public class Stat
{
public int level;
public int hp;
public int attack;
}
[Serializable]
public class StatData
{
public List<Stat> stats = new List<Stat>();
}
public void Init()
{
TextAsset textAsset = Resources.Load<TextAsset>("Data/StatData");
StatData data = JsonUtility.FromJson<StatData>(textAsset.text);
}
[Serializable] 붙여줘야 함
JsonUtility.FromJson<>(); 사용 ==> List형태로 저장됨
위처럼 Json의 내용을 클래스로 쪼개서 최종적으로는 List형태로 저장이 됩니다.
(위 코드에선 stats 리스트에 모든 내용이 저장됨.)
이때 주의점은, level,hp,attack,stats의 이름이 반드시 Json에 있는 단어와 같아야 합니다.
자료형도 같아야 합니다.
그리고 접근지정자는 public또는 [SerializeField]를 붙여줘야 합니다.
그러나, List보다는 딕셔너리를 사용해서 Key를 통해 접근하는 것이 아무래도 좋겠죠?
[Serializable]
public class Stat
{
public int level;
public int hp;
public int attack;
}
[Serializable]
public class StatData
{
public List<Stat> stats = new List<Stat>();
}
public void Init()
{
public Dictionary<int, Stat> StatDict {get; private set;} = new Dictionary<int,Stat>();
TextAsset textAsset = Resources.Load<TextAsset>("Data/StatData");
StatData data = JsonUtility.FromJson<StatData>(textAsset.text);
foreach(Stat stat in data.stats) //딕셔너리로 변환해주는 과정
StatDict.Add(stat.level,stat);
}
마지막 2줄을 통해서 리스트를 딕셔너리로 변환해 줄 수 있습니다.
(data.stats.ToDictionary();를 사용해도 되는 것으로 알지만 과거 ios쪽 버그가 있어서 꺼린다고 합니다..?)
데이터 매니저 및 데이터구조 따로 관리(참고)
/*데이터 매니저*/ //DataManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface ILoader<Key, Value>
{
Dictionary<Key, Value> MakeDict();
}
public class DataManager
{
public Dictionary<int, Stat> StatDict { get; private set; } = new Dictionary<int, Stat>(); //외부에서 얘를 뽑아서 사용하게 될 것임.
public void Init()
{
StatDict = LoadJson<StatData, int, Stat>("StatData").MakeDict();
}
Loader LoadJson<Loader, Key, Value>(string path) where Loader : ILoader<Key, Value>
{
TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/{path}");
return JsonUtility.FromJson<Loader>(textAsset.text);
}
}
/*받아올 Json데이터 구조를 따로 관리*/ //Data.Contents.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#region Stat
[Serializable]
public class Stat
{
public int level;
public int hp;
public int attack;
}
[Serializable]
public class StatData : ILoader<int, Stat>
{
public List<Stat> stats = new List<Stat>();
public Dictionary<int, Stat> MakeDict()
{
Dictionary<int, Stat> dict = new Dictionary<int, Stat>();
foreach (Stat stat in stats)
dict.Add(stat.level, stat);
return dict;
}
}
#endregion
저는 위 방식을 사용해서 Json을 읽고 있습니다.
'유니티' 카테고리의 다른 글
[Unity] 헤더추가로 인스펙터 깔끔하게 정리하기! (0) | 2023.02.18 |
---|---|
[Unity] 애니메이션 이벤트 (0) | 2023.02.18 |
[Unity] 코루틴(Coroutine) (0) | 2023.02.02 |
[Unity] 애니메이션 및 행동 관리하기(with 스테이트 패턴) (0) | 2023.01.30 |
[Unity] 애니메이션 기초(스테이트 머신) 및 파라미터 설정 (0) | 2023.01.28 |