게임에서는 여러가지 정보들이 존재한다. 레벨, 아이템 등 정보를 저장하기 위해서는 다른 저장 공간을 사용하고, 불러오는 형태로 게임을 제작한다. 코드 내에 데이터를 저장하고 빌드하면 되는 일인데 왜 굳이 분리를 하냐? 라는 의문이 생길 수도 있다. 예시를 들어보면, 만약 구글 플레이 스토어나 애플 앱스토어에 게임을 올려놓은 개발자라고 해보자. 이 상황에서 밸런스 패치를 진행하여 새로 앱을 빌드하고 스토어에 올리면, 일정 기간의 심의 기간을 거쳐서 올라가게 된다. 그러나 분리를 시켜 서버에서 데이터를 불러오게 관리를 한다면 서버의 데이터 파일만 수정하게 된다면 스토어의 심의 없이 수정이 가능하기 때문이다.

 

이번 코드에서는 Json의 형태로 데이터를 만들었다.

 

DataManager.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public interface ILoader<Key, Value>
{ // ILoader 인터페이스를 상속받는 객체들은 무조건 딕셔너리를 만든다.
    Dictionary<Key, Value> MakeDict();
}

public class DataManager
{
	// 게임의 스탯을 저장하는 StatDict 생성
    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>
    { // Resource/Data/path 에 존재하는 Json 파일을 불러온다.
        TextAsset textAsset = Managers.Resource.Load<TextAsset>($"Data/{path}");
        return JsonUtility.FromJson<Loader>(textAsset.text);
    }
}

 

StatData 클래스는 DataContents.cs에 선언해 두었다.

 

DataContents.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

 

StatData.json

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

  ]
}

 

게임 씬에서 아래의 코드를 통해 데이터를 불러올 수 있다.

 

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

 

Managers에서 DataManager에 접근하여 StatDict를 가져온다.

dict에 접근하여 데이터를 보는 것이다.

'UNITY' 카테고리의 다른 글

UNITY - Coroutine  (0) 2024.01.23
UNITY - Object Pooling  (1) 2024.01.23
UNITY - SoundManager  (0) 2024.01.22
UNITY - UI 자동화 - 게임 UI 구현  (0) 2024.01.22
UNITY - Scene  (1) 2024.01.12

+ Recent posts