ShovelingLife
A Game Programmer
ShovelingLife
전체 방문자
오늘
어제
  • 분류 전체보기 (1067)
    • 그래픽스 (57)
      • 공통 (19)
      • 수학 물리 (22)
      • OpenGL & Vulkan (1)
      • DirectX (14)
    • 게임엔진 (180)
      • Unreal (69)
      • Unity (100)
      • Cocos2D-X (3)
      • 개인 플젝 (8)
    • 코딩테스트 (221)
      • 공통 (7)
      • 프로그래머스 (22)
      • 백준 (162)
      • LeetCode (19)
      • HackerRank (2)
      • 코딩테스트 알고리즘 (8)
    • CS (235)
      • 공통 (21)
      • 네트워크 (44)
      • OS & 하드웨어 (55)
      • 자료구조 & 알고리즘 (98)
      • 디자인패턴 (6)
      • UML (4)
      • 데이터베이스 (7)
    • 프로그래밍 언어 (346)
      • C++ (167)
      • C# (88)
      • Java (9)
      • Python (33)
      • SQL (30)
      • JavaScript (8)
      • React (7)
    • 그 외 (9)
      • Math (5)
      • 일상 (5)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • Source Code 좌측 상단에 복사 버튼 추가 완료
  • 언리얼 엔진 C++ 빌드시간 단축 꿀팁
  • 게임 업계 코딩테스트 관련
  • 1인칭 시점으로 써내려가는 글들

인기 글

태그

  • 포인터
  • 클래스
  • C
  • 배열
  • string
  • 언리얼
  • 오블완
  • 함수
  • 프로그래머스
  • 문자열
  • 티스토리챌린지
  • 파이썬
  • SQL
  • 유니티
  • 백준
  • 알고리즘
  • 그래픽스
  • Unity
  • C++
  • c#

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ShovelingLife

A Game Programmer

[Unity] Serializable Dictionary - 인스펙터에 노출시킬 수 있는 딕셔너리
게임엔진/Unity

[Unity] Serializable Dictionary - 인스펙터에 노출시킬 수 있는 딕셔너리

2023. 1. 14. 12:31
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace AT.SerializableDictionary
{
    [System.Serializable]
    public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, ISerializationCallbackReceiver
    {
        [SerializeField]
        private List<TKey> keys = new List<TKey>();

        [SerializeField]
        private List<TValue> values = new List<TValue>();

        // save the dictionary to lists
        public void OnBeforeSerialize()
        {
            keys.Clear();
            values.Clear();
            foreach (KeyValuePair<TKey, TValue> pair in this)
            {
                keys.Add(pair.Key);
                values.Add(pair.Value);
            }
        }

        // load dictionary from lists
        public void OnAfterDeserialize()
        {
            this.Clear();

            if (keys.Count != values.Count)
                throw new System.Exception(string.Format("there are {0} keys and {1} values after deserialization. Make sure that both key and value types are serializable."));

            for (int i = 0; i < keys.Count; i++)
                this.Add(keys[i], values[i]);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

namespace AT.HUDSystem
{
    public enum HUD_OBJECT_TYPE
    {
        Damage_Normal,
        Damage_Critical,
    }

    [System.Serializable]
    public class DictionaryOfHUDTypeAndTextMesh : AT.SerializableDictionary.SerializableDictionary<HUD_OBJECT_TYPE, TextMeshPro> { }

    [System.Serializable]
    public class DictionaryOfPoolBase : AT.SerializableDictionary.SerializableDictionary<HUD_OBJECT_TYPE, List<TextMeshPro>> { }

    public class HUDSystem : MonoBehaviour
    {
        /// <summary> HUD System Prefab List </summary>
        public DictionaryOfHUDTypeAndTextMesh prefabList = new DictionaryOfHUDTypeAndTextMesh();

        /// <summary> HUD System Pool Container </summary>
        public DictionaryOfPoolBase pools = new DictionaryOfPoolBase();

        public void Initialize()
        {
            pools.Clear();
            foreach (var obj in prefabList)
            {
                List<TextMeshPro> poolList = new List<TextMeshPro>();
                pools.Add(obj.Key, poolList);
            }
        }

        public TextMeshPro CreateItem(HUD_OBJECT_TYPE type)
        {
            if (prefabList.ContainsKey(type))
            {
                TextMeshPro newTextMesh = Instantiate(prefabList[type]);
                newTextMesh.transform.position = Vector3.zero;
                return newTextMesh;
            }

            Debug.LogErrorFormat("Can not Find Target HUD Object. Type : {0}", type.ToString());
            return null;
        }

        public TextMeshPro GetItem(HUD_OBJECT_TYPE type)
        {
            for (int i = 0; i < pools[type].Count; i++)
            {
                if (!pools[type][i].gameObject.activeSelf)
                    return pools[type][i];
            }

            return CreateItem(type);
        }
    }
}

출처 : [은고] 게임 프로그래밍 :: C# Unity - Serializable Dictionary (tistory.com)

저작자표시 (새창열림)

'게임엔진 > Unity' 카테고리의 다른 글

[Unity] Job 시스템 이해 2, NativeContainer  (0) 2023.01.15
[Unity] Job 시스템 이해 1, IJob  (0) 2023.01.15
[Unity] onClick.AddListener에서 함수의 파라미터 전달 문제  (0) 2023.01.14
[Unity] 안드로이드 플러그인 사용해보기  (0) 2023.01.09
[Unity] 강체(RigidBody) AddForce에 대한  (0) 2022.12.07
    '게임엔진/Unity' 카테고리의 다른 글
    • [Unity] Job 시스템 이해 2, NativeContainer
    • [Unity] Job 시스템 이해 1, IJob
    • [Unity] onClick.AddListener에서 함수의 파라미터 전달 문제
    • [Unity] 안드로이드 플러그인 사용해보기
    ShovelingLife
    ShovelingLife
    Main skill stack => Unity C# / Unreal C++ Studying Front / BackEnd, Java Python

    티스토리툴바