07
27

Dictionary(딕셔너리)란?

키(key)와 값(value)으로 이루어진 데이터 구조이다.

키는 각각의 값에 대한 고유한 식별자 역할을 하며, 값을 찾거나 접근하는 데에 사용된다.

컬렉션의 성능 문제를 해결하기 위해 나온 것으로, Hastable의 제너릭 버전이다.
따라서 스크립트에서 사용 시 using System.Collections.Generic; 선언해야 사용이 가능하다.

예제

게임에서 아이템에 대한 정보를 저장해야 할 때
using UnityEngine;
using System.Collections.Generic;

public class ItemDatabase : MonoBehaviour
{
    // 아이템 데이터를 저장할 Dictionary
    private Dictionary<int, Item> itemDict = new Dictionary<int, Item>();

    // 아이템 클래스
    public class Item
    {
        public string name;
        public int price;
        public string description;
        // 추가적인 아이템 정보...
    }

    // 아이템 데이터를 초기화하는 함수
    private void InitializeItems()
    {
        Item item1 = new Item();
        item1.name = "Health Potion";
        item1.price = 100;
        item1.description = "Restores health when consumed.";
        itemDict.Add(1, item1);

        Item item2 = new Item();
        item2.name = "Magic Scroll";
        item2.price = 200;
        item2.description = "Unleashes powerful magic when used.";
        itemDict.Add(2, item2);

        // 추가적인 아이템 정보를 초기화...
    }

    // 아이템 정보를 반환하는 함수
    public Item GetItem(int itemID)
    {
        if (itemDict.ContainsKey(itemID))
        {
            return itemDict[itemID];
        }
        else
        {
            Debug.LogWarning("Item with ID " + itemID + " not found!");
            return null;
        }
    }
}
위 코드에서 ItemDatabase 클래스는 아이템 데이터를 저장하고 관리하는 역할을 한다.

Item 클래스는 아이템에 대한 정보를 담은 클래스로, 이름, 가격, 설명 등의 정보를 포함한다.

InitializeItems 함수에서는 아이템 데이터를 초기화하고, GetItem 함수를 통해 아이템의 정보를 반환할 수 있다.

 

COMMENT