이번 시간에는 Unity에서 사용하는 자료구조에 대해 알아보고 활용해보는 시간을 가지겠다.
자료구조란 데이터를 효율적으로 저장하고, 관리하고, 사용할 수 있도록 조직화 할 수 있는 방식을 말한다.
데이터를 배치하고 수정할 때 빠르고 효율적으로 처리해주는 구조이다.
게임에서 또한 플레이어 정보, 몬스터 정보, 맵 정보 등 정말 다양한 데이터들이 존재하기 때문에 다양한 자료구조가 있으며 이번 시간에는 Unity에서 사용하는 자료구조를 살펴보고자 한다.
1. 배열 (Array)
using UnityEngine;
public class EnemyManager : MonoBehaviour
{
public GameObject[] enemies; // 에디터에서 드래그 앤 드롭
void Start()
{
for (int i = 0; i < enemies.Length; i++)
{
enemies[i].SetActive(true);
}
}
}
⦁ 정의: 크기가 고정된 자료구조
⦁ 활용도: 미리 배치된 적 오브젝트들을 배열로 관리
2. List<T> (리스트)
using UnityEngine;
using System.Collections.Generic;
public class BulletManager : MonoBehaviour
{
private List<GameObject> bullets = new List<GameObject>();
public void AddBullet(GameObject bullet)
{
bullets.Add(bullet); // 총알 등록
}
public void RemoveBullet(GameObject bullet)
{
bullets.Remove(bullet); // 총알 제거
}
void Update()
{
Debug.Log("현재 총알 수: " + bullets.Count);
}
}
⦁ 정의: 크기가 가변적인 배열
⦁ 활용도: 스폰된 총알, NPC, 몬스터 같은 오브젝트들을 동적으로 관리
3. Dictionary <TKey, TValue>
using UnityEngine;
using System.Collections.Generic;
public class ItemDatabase : MonoBehaviour
{
private Dictionary<int, string> items = new Dictionary<int, string>();
void Start()
{
// 아이템 등록
items.Add(1, "포션");
items.Add(2, "하이포션");
items.Add(3, "에테르");
// 특정 ID 검색
Debug.Log("아이템 2번은: " + items[2]);
}
}
⦁ 정의: Key-Value로 이루어진 데이터 쌍 저장 자료구조
⦁ 활용도: 아이템 ID -> 아이템 이름, NPC 이름 -> 대사 매핑
4. Queue<T> (큐, FIFO 구조)
using UnityEngine;
using System.Collections.Generic;
public class AIActionQueue : MonoBehaviour
{
private Queue<string> actions = new Queue<string>();
void Start()
{
actions.Enqueue("이동");
actions.Enqueue("공격");
actions.Enqueue("회피");
Debug.Log(actions.Dequeue()); // "이동"
Debug.Log(actions.Dequeue()); // "공격"
}
}
⦁ 정의: 선입선출 자료구조
⦁ 활용도: 적 AI 행동 순서, 이벤트 처리
5. Stack<T> (스택, LIFO 구조)
using UnityEngine;
using System.Collections.Generic;
public class StateManager : MonoBehaviour
{
private Stack<string> states = new Stack<string>();
void Start()
{
states.Push("Idle");
states.Push("Move");
states.Push("Attack");
Debug.Log(states.Pop()); // "Attack"
Debug.Log(states.Pop()); // "Move"
}
}
⦁ 정의: 후입선출 자료구조
⦁ 활용도: 상태 전환(Undo/Redo), 게임 모드 되돌리기
6. HashSet<T>
using UnityEngine;
using System.Collections.Generic;
public class EnemyTracker : MonoBehaviour
{
private HashSet<int> defeatedEnemies = new HashSet<int>();
public void DefeatEnemy(int enemyId)
{
if (!defeatedEnemies.Contains(enemyId))
{
defeatedEnemies.Add(enemyId);
Debug.Log(enemyId + "번 적을 처음 처치!");
}
else
{
Debug.Log(enemyId + "번 적은 이미 처치됨.");
}
}
}
⦁ 정의: 중복 없는 집합, 포함 여부 빠르게 확인
⦁ 활용도: 클리어한 적, 흭득한 업적 관리
7. Transform Tree (계층 구조)
using UnityEngine;
public class HierarchyExample : MonoBehaviour
{
void Start()
{
foreach (Transform child in transform)
{
Debug.Log("자식 오브젝트: " + child.name);
}
}
}
⦁ 정의: GameObject 간 부모-자식 구조
⦁ 활용도: UI, 캐릭터 뼈대, 자식 오브젝트 제어
8. ScriptableObject (데이터 저장용)
using UnityEngine;
[CreateAssetMenu(fileName = "NewItem", menuName = "Game/Item")]
public class Item : ScriptableObject
{
public string itemName;
public int price;
}
⦁ 정의: 게임 내 데이터 자산 관리 자료구조
⦁ 활용도: 아이템, 몬스터 스탯, 스킬 데이터 등 에셋으로 관리
9. NativeArray (Job System용)
using Unity.Collections;
using UnityEngine;
public class NativeArrayExample : MonoBehaviour
{
void Start()
{
NativeArray<int> numbers = new NativeArray<int>(5, Allocator.Temp);
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = i * 10;
}
foreach (int num in numbers)
{
Debug.Log(num);
}
numbers.Dispose(); // 반드시 메모리 해제 필요
}
}
⦁ 정의: 고성능 병렬 연산 지원 (DOTS/ECS 환경에서 주로 사용)
⦁ 활용도: 대량의 데이터(물리 연산, AI 시뮬레이션) 최적화
'프로그래밍 > Unity 문법' 카테고리의 다른 글
Unity Delegate, Action, Func (0) | 2025.09.30 |
---|---|
Unity get / set (0) | 2025.09.17 |
Unity 스크립트 기본 클래스 정리 (0) | 2025.09.12 |