🔍 요소 찾기(Query)
✅ 이름으로 찾기
이름이 "OK"인 모든 요소:
List<VisualElement> result = root.Query("OK").ToList();
이름이 "OK"인 첫 번째 요소:
VisualElement result = root.Query("OK").First(); // 또는 더 간단히 VisualElement result = root.Q("OK");
이름이 "OK"인 두 번째 요소:
VisualElement result = root.Query("OK").AtIndex(1);
이름이 "OK"인 마지막 요소:
VisualElement result = root.Query("OK").Last();
🎨 USS 클래스 이름으로 찾기
클래스가 "yellow"인 모든 요소:
List<VisualElement> result = root.Query(className: "yellow").ToList();
클래스가 "yellow"인 첫 번째 요소:
VisualElement result = root.Q(className: "yellow");
🧩 요소 타입으로 찾기
첫 번째 Button 요소 찾기:
Button btn = root.Q<Button>(); btn.tooltip = "This is a tooltip!";
세 번째 Button 요소 찾기:
Button btn = root.Query<Button>().AtIndex(2);
주의: 요소의 실제 타입으로만 쿼리할 수 있으며, 부모 클래스 타입으로는 불가능합니다.
🧠 조건(Predicate)으로 찾기
"yellow" 클래스를 가지며 tooltip이 비어 있는 요소들:
List<VisualElement> result = root.Query(className: "yellow") .Where(elem => elem.tooltip == "").ToList();
🧩 복합 쿼리
이름이 "OK"이고 클래스가 "yellow"인 첫 번째 Button:
VisualElement result = root.Query<Button>(className: "yellow", name: "OK").First();
"container2"의 자식 중 "Cancel"이라는 이름의 Button:
VisualElement result = root.Query<VisualElement>("container2") .Children<Button>("Cancel").First();
🔧 결과 처리하기
tooltip이 없는 모든 요소에 tooltip 추가:
root.Query() .Where(elem => elem.tooltip == "") .ForEach(elem => elem.tooltip = "This is a tooltip!");
🧭 베스트 프랙티스
- UQuery는 트리 구조를 탐색하므로, 초기화 시 캐싱해두는 것이 성능에 좋습니다.
- 여러 요소를 검색할 때는 Query().ToList()보다는 QueryState를 순회하세요.
- foreach (var elem in root.Query(className: "yellow"))
{
elem.tooltip = "노란 요소!";
}
- foreach (var elem in root.Query(className: "yellow"))
- UIDocument이나 EditorWindow보다 오래 사는 클래스에 VisualElement를 참조로 남기지 마세요. → GC 누수 위험
- VisualElement를 람다 클로저에서 사용할 경우, 꼭 변수로 캡처하세요.
- 요소를 자주 생성/제거할 경우 증분 GC(incremental GC) 사용을 고려하세요.
'Unity > UI ToolKit' 카테고리의 다른 글
C# 스크립트를 사용하여 UI 구조화 (0) | 2025.05.11 |
---|---|
UXML 및 USS C# 스크립트 로드 방법 (0) | 2025.05.11 |
순서변경 (0) | 2025.05.11 |