BG Database 사용법 4 : Code Generation

#. 에셋스토어 링크

https://assetstore.unity.com/packages/tools/integration/bg-database-112262?aid=1101l7zGS

 

BG Database | 기능 통합 | Unity Asset Store

Use the BG Database from BansheeGz on your next project. Find this integration tool & more on the Unity Asset Store.

assetstore.unity.com

 

https://www.bansheegz.com/BGDatabase/CodeGeneration/

BGDatabase에서 가장 강력한 기능.

데이터에 빠른 접근이 가능하도록 CodeGeneration이라는 것을 지원합니다.

 

일반적인 DB 에셋들에서는 string을 사용해서 데이터를 불러오기 때문에, 오타의 우려가 있습니다.

이를 보완하기 위해 자동 생성 클래스를 만들어서 유효성검사를 할 수 있는 기능입니다.

 

#. Code Generation 설정하기

1) Addons 탭에서 CodeGen 창을 열고 Enable을 눌러 사용설정창을 엽니다.

2) 각 설정은 다음과 같습니다.

 - Code Generator : 우측의 Use default 버튼을 누르면 자동으로 값을 채웁니다. 

 - Source File : 프로젝트에 빈 스크립트 파일(.cs)을 하나 만들어서 설정합니다. Editor 폴더에 넣으시면 안됩니다.

 

프리픽스는 철저히 취향의 영역이기 때문에 협업하시는 팀원이 있다면 같이 테스트를 해보며 정하는 것을 추천합니다.

저는 개인적으로 왼손으로 칠 수 있는 글자를 단일 문자(D_ / f_)로 할 때 빠르게 칠 수 있어서 활용성이 있었습니다.

 - Class names prefix : BG_ / DB_ / D_ 등등 취향에 따라서 짧은 이름을 추천합니다.

 - Field names prefix : 역시 f_ 등의 짧은 이름을 추천합니다. 

 

 - 나머지 빈칸들은 취향상 따로 지정하지 않았습니다.

 

 

#. Code Generation을 통해 데이터 가져오기

시트 이름이 Shop_Product 인 첫 번째 줄의 string 자료형인 subTitle 필드 가져오기

 

CodeGeneration을 사용하지 않았을 때

// meta (시트) 가져오기. "" 안에는 시트이름. 
var meta = BGRepo.I["Shop_Product"];
// 개별 entity (가로 줄) 가져오기. () 안에는 entity Name, ID, Index 중 한개를 인자로 받음
var entity = meta.GetEntity(0);
// 하나의 필드 값을 가져옴. string <> 안에는 자료형, "" 안에는 필드 명
var fieldValue = entity.Get<string>("subTitle");

CodeGeneration을 사용했을 때 ( Class Prefix : D_ / Field prefix : f_ )

// 개별 entity (가로 줄) 가져오기. () 안에는 entity Name, ID, Index 중 한개를 인자로 받음
var entity = D_Shop_Product.GetEntity(0);
// 하나의 필드 값을 가져옴.
var fieldValue = entity.f_subTitle;

string이 완전히 제거되었습니다! 때문에 오타가 날 여지가 없어집니다.

DB의 필드를 추가하거나 이름이 수정된 경우 CodeGen 버튼을 다시 눌러 업데이트해야 합니다.

 

 

#. 모든 데이터를 한번에 캐싱하고 싶을 때

그런데 entity Name이나 ID, Index 값을 알아야만 가져올 수 있다는 사실은 변하지 않습니다. >(Key 업데이트로 개선됨)

때문에 저는 복잡한 데이터의 경우 미리 리스트나 딕셔너리에 캐싱해놓고 쓰는걸 선호합니다.

시트 이름이 Shop_Product 인 데이터를 가공하여 ShopProduct라는 클래스를 만들고, 
List<ShopProduct> 에 캐싱하기.
List<ShopProduct> shopProducts = new List<ShopProduct>();
List<BGEntity> entitys = BGRepo.I["Shop_Product"].EntitiesToList();
foreach (var entity in entitys)
    {
        ShopProduct shopProduct = new ShopProduct
        (
            entity.Index,
            entity.Get<int>("shopIndex"),
            entity.Get<int>("listIndex"),
            entity.Get<int>("colorIndex"),
            entity.Get<string>("title"),
            entity.Get<string>("subTitle"),
            new string[3] { entity.Get<string>("slotA"), entity.Get<string>("slotB"), entity.Get<string>("slotC") },
            new float[4] { entity.Get<float>("prob_common"), entity.Get<float>("prob_magic"), entity.Get<float>("prob_rare"), entity.Get<float>("prob_legend") },
            entity.Get<int>("price"),
            entity.Get<float>("salePoint")
        );

        shopProducts.Add(shopProduct);
    }

CodeGeneration을 사용했을 때

List<ShopProduct> shopProducts = new List<ShopProduct>();

D_Shop_Product.ForEachEntity(
        entity => 
        {
            ShopProduct shopProduct = new ShopProduct
            (
                entity.Index,
                entity.f_shopIndex,
                entity.f_listIndex,
                entity.f_colorIndex,
                entity.f_title,
                entity.f_subTitle,
                new string[3] { entity.f_slotA, entity.f_slotB, entity.f_slotC },
                new float[4] { entity.f_prob_common, entity.f_prob_magic, entity.f_prob_rare, entity.f_prob_legend },
                entity.f_price,
                entity.f_salePoint
            );

            shopProducts.Add(shopProduct);
        }
    );

 

 

#. 필터링을 통해 특정 Entity만 가져오기

특정 값을 필터링 하여 엔티티를 가져오는 것도 가능합니다.

// 검색된 첫번째 Entity를 반환한다. (따라서 Unique 를 사용하는게 좋다)
var entity = D_Sheet.FindEntity(e => e.f_myString == "검색할키값");

// 조건을 만족하는 Entity들을 반환한다.
var entityList = D_Sheet.FindEntities(e => e.f_myString == "검색할키값");

 

#. keys를 정의해 필터링하기

자주 필터링 해야되는 값이 있다면 Keys를 지정하여 가져오는 것이 간편합니다.

1) Meta 설정에서 Keys 탭을 눌러서 키 탭을 엽니다.

 

2) 필터링하고자하는 필드를 선택합니다. 여기서는 string타입의 myString를 지정하겠습니다.

   Name은 임의로 지정하면 됩니다. myStringKey 로 지정하겠습니다.

 

3) myString을 Add 한 뒤, Name은 알아보기 쉽도록 myStringKey로 지정한 뒤 Create를 합니다. 

 

4) Key를 코드에서 사용하기 위해 CodeGen 버튼을 눌러서 업데이트해줍니다.

 

5) 이제 코드에서는 다음과 같이 접근이 가능합니다.

   EntityByKey는 단일(Unique) 엔티티를 반환하며, EntitiesByKey는 조건을 만족하는 엔티티의 리스트를 반환합니다.

// 두가지 방법으로 접근 가능합니다.
var entity1 = D_Sheet._myStringKey.GetEntityByKey("검색할키값");
var entity2 = D_Sheet.GetEntityByKeymyStringKey("검색할키값");

// 조건을 만족하는 복수 엔티티를 반환하는 메서드도 존재합니다.
var entity1 = D_Sheet._myStringKey.GetEntitiesByKey("검색할키값");
var entity2 = D_Sheet.GetEntitiesByKeymyStringKey("검색할키값");

 

 

 

 

댓글

Designed by JB FACTORY