새소식

⇥ 2D Game/Unity

Unity 게임 만들기 프로젝트 - DataManager

  • -
반응형

1. Data Manager

서버나 혹은 클라이언트에서 데이터를 모두 들고 있으면 과부하가 걸리고, 관리에 용이하지 않다.
그래서 대부분의 정보를 json 형식으로 data 파일로 관리하고, 서버와 클라이언트는 해당 data 파일을 통신하여 정보를 교환하는 식으로 데이터를 관리하게 된다.

# StatData

{
  "stats": [
    {
      "level": "1",
      "hp": "100",
      "attack": "10"
    },
    {
      "level": "2",
      "hp": "150",
      "attack": "15"
    },
    {
      "level": "3",
      "hp": "200",
      "attack": "20"
    }
  ]
}

stats 라는 데이터가 담긴 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 형식에 맞게, Stat 클래스를 구성한다. 이 때 각 변수들의 이름은 동일해야 정상적으로 읽어들일 수 있다.
그리고 StatData 클래스를 구성할 때 stats 리스트는 json 의 배열을 담게 된다.

public Dictionary<int, Stat> MakeDict() : MakeDict 함수는 int 와 Stat 클래스로 구성된 딕셔너리 이다.
위에서 받은 List 데이터를 이용하여 dict 에 level 을 key 값으로 가지고, stat class 를 value로 가지는 딕셔너리가 생성된다.
즉 리스트를 딕셔너리로 변환하는 역할을 한다.

# 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);
    }
}

ILoader 는 인터페이스로 MakeDict 를 선언해준다. 위에서 MakeDict 함수를 만들어주었다.
StatDict 라는 딕셔너리를 DataManager 가 들고 있으며, 초기화 시에 LoadJson 을 하게 된다.

Loader LoadJson<Loader, Key, Value>(string path) where Loader : ILoader<Key, Value> 
Loader 는 ILoader 인터페이스를 상속받고, 따라서 무조건 MakeDict 가 포함된 형식임을 알 수 있다.

JSON 파일을 로드하고, JsonUtility.FromJson<Loader>(textAsset.text)를 통해
JSON 문자열을 StatData 객체로 변환한다.

Dictionary<int, Stat> dict = Managers.Data.StatDict;

코드에서 위와 같이 dict 를 생성하고, StatDict를 선언해주면 
DataManager 의 StatDict 딕셔너리가 생성, Init 이 실행되면서 자연스럽게 데이터가 저장된 딕셔너리가 로드된다.

 

즉 DataManager 의 Init 호출
-> LoadJson 으로 StatData.json 호출하여 StatData 객체로 변환 
-> 변환된 StatData 객체의 MakeDict 를 호출하여 리스트를 딕셔너리로 변환 (key : level, value : stat객체)
-> 해당 딕셔너리가 StatDict 에 저장

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.