포스트

섹션12. DataManager

위 글은 인프런에 있는 Rookiss님의 [C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part3: 유니티 엔진 강의를 듣고 남긴 필기입니다.

DataManager

  • 게임에 존재하는 모든 수치들을 관리하는 DataManager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/// <summary>
/// 읽어들이는 데이터의 포맷 클래스는 ILoader인터페이스를 구현해야 함.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public interface ILoader<TKey, TValue>
{
    Dictionary<TKey, TValue> 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();
    }

		// 실제로 Json에서 읽는 기능을 넣은 인터페이스 메소드. 제네릭을 활용해 유연하게 동작할 수 있도록.
    TLoader LoadJson<TLoader, TKey, TValue>(string path) where TLoader : ILoader<TKey, TValue>
    {
        TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/{path}");
        return JsonUtility.FromJson<TLoader>(textAsset.text);
    }
}
  • 읽어들이는 데이터의 포맷 클래스.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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 (var item in stats)
            dict.Add(item.level, item);

        return dict;
    }
}

#endregion
  • 데이터를 담고 있는 파일 (=게임에 쓰일 데이터가 저장되어있는 파일)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
  "stats" : [
    {
      "level" : "1",
      "hp" : "100",
      "attack" : "10"
    },
    {
      "level" : "2",
      "hp" : "150",
      "attack" : "15"
    },
    {
      "level" : "3",
      "hp" : "200",
      "attack" : "20"
    }
  ]
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.