Unity UQuery 사용 매뉴얼
Unity의 UQuery 기능은 UI 요소를 효율적으로 찾기 위한 매우 유용한 도구입니다. 이 매뉴얼은 UQuery의 기본 개념과 사용 방법을 설명합니다.
UQuery란?
UQuery는 시각적 트리에서 요소를 찾기 위한 쿼리 시스템입니다. JQuery와 Linq에서 영감을 받아 제작되었으며, 모바일 플랫폼에서 최적화를 위해 동적 메모리 할당을 제한하도록 설계되었습니다.
UQuery 사용 방법
UQuery를 사용하려면 먼저 UXML을 로드하고 인스턴스화해야 합니다. 이후 Query
또는 Q
메서드를 사용하여 요소를 찾을 수 있습니다.
기본 문법
Query
메서드는 선택 규칙과 일치하는 요소 리스트를 반환합니다.Q
는Query<T>.First()
의 약어로 첫 번째 요소를 찾습니다.
코드 예제
아래의 UXML 예제를 사용해 보겠습니다.
<UXML xmlns="UnityEngine.UIElements">
<VisualElement name="container1">
<Button name="OK" text="OK" />
<Button name="Cancel" text="Cancel" />
</VisualElement>
<VisualElement name="container2">
<Button name="OK" class="yellow" text="OK" />
<Button name="Cancel" text="Cancel" />
</VisualElement>
<VisualElement name="container3">
<Button name="OK" class="yellow" text="OK" />
<Button name="Cancel" class="yellow" text="Cancel" />
</VisualElement>
</UXML>
이름으로 쿼리하기
이름으로 요소를 찾으려면 아래와 같이 사용할 수 있습니다.
List<VisualElement> result = root.Query("OK").ToList();
VisualElement firstResult = root.Query("OK").First();
USS 클래스로 쿼리하기
USS 클래스를 이용해 요소를 찾는 방법입니다.
List<VisualElement> result = root.Query(className:"yellow").ToList();
VisualElement firstResult = root.Q(className:"yellow");
요소 타입으로 쿼리하기
C# 타입을 사용해 특정 요소를 찾는 방법입니다.
VisualElement result = root.Q<Button>();
result.tooltip = "This is a tooltip!";
술어로 쿼리하기
Where 메서드를 사용해 술어를 만족하는 모든 요소를 선택합니다.
List<VisualElement> result = root.Query(className:"yellow").Where(elem => elem.tooltip == "").ToList();
복잡한 계층적 쿼리
이름, 클래스, 타입을 결합하여 복잡한 쿼리를 만들 수 있습니다.
VisualElement result = root.Query<Button>(className:"yellow", name:"OK").First();
결과에 대한 작업
ForEach 메서드를 사용하여 쿼리 결과에 직접 작업할 수 있습니다.
root.Query().Where(elem => elem.tooltip == "").ForEach(elem => elem.tooltip="This is a tooltip!");
베스트 프랙티스
- 캐싱 - UQuery의 캐시 결과를 활용하여 성능을 향상시킵니다.
- QueryState 사용 - 여러 요소를 검색할 경우 QueryState 구조체를 사용하여 리스트 생성 비용을 줄입니다.
- 가비지 컬렉션 관리 -VisualElement 변수의 레퍼런스 관리를 주의하여 가비지 컬렉터의 성능을 최적화합니다.
참고 자료
위 내용을 바탕으로 Unity의 UQuery를 이해하고 활용하는 데 도움이 되기를 바랍니다. 다양한 예제를 통해 실습해보세요!