C#의 인덱서(Indexer)는 배열처럼 객체 인스턴스를 [] 연산자로 접근할 수 있게 해 주는 특별한 프로퍼티. Unity에서도 커스텀 컬렉션(예: 인벤토리, 그리드 등)을 구현할 때 유용하게 쓰인다.
public class MyCollection
{
private int[] _array = new int[10];
// 이 부분이 인덱서
public int this[int index]
{
get
{
// 예외 처리 등 자유롭게 추가 가능
if (index < 0 || index >= _array.Length)
throw new IndexOutOfRangeException();
return _array[index];
}
set
{
if (index < 0 || index >= _array.Length)
throw new IndexOutOfRangeException();
_array[index] = value;
}
}
}
this[int index] 부분이 “여기에 [] 인덱스를 받을 것이다” 선언부get/set 안에서 내부 배열이나 컬렉션에 접근하도록 구현myCollection[3] = 42; 혹은 var x = myCollection[3]; 처럼 배열처럼!
using UnityEngine;
using System.Collections.Generic;
public class Inventory : MonoBehaviour
{
// 예시 아이템 클래스
[System.Serializable]
public class Item
{
public string itemName;
public Sprite icon;
}
// 인벤토리 슬롯
[SerializeField] private List<Item> _items = new List<Item>(20);
// 인덱서 정의
public Item this[int slot]
{
get
{
if (slot < 0 || slot >= _items.Count)
return null;
return _items[slot];
}
set
{
if (slot < 0 || slot >= _items.Count)
return;
_items[slot] = value;
}
}
// 예: 슬롯 개수 프로퍼티
public int SlotCount => _items.Count;
}
public class InventoryTest : MonoBehaviour
{
public Inventory inventory;
void Start()
{
// 0번 슬롯에 아이템 할당
inventory[0] = new Inventory.Item { itemName = "Potion" };
// 0번 슬롯 아이템 읽기
var firstItem = inventory[0];
Debug.Log("첫 번째 아이템: " + firstItem?.itemName);
}
}
이렇게 하면 inventory[0] 형태로 간단히 접근할 수 있어,
슬롯마다 GetItem(0), SetItem(0, itm) 같은 메서드를 일일이 만들 필요가 없어집니다.
2D 그리드 같은 경우엔 파라미터를 두 개 받을 수도 있다.
public class TileGrid
{
private Tile[,] _tiles;
public TileGrid(int width, int height)
{
_tiles = new Tile[width, height];
}
public Tile this[int x, int y]
{
get => _tiles[x, y];
set => _tiles[x, y] = value;
}
}
grid[3,5] = someTile; 처럼 쓸 수 있음.