UQuery受到JQuery
與Linq
啟發,UQuery被設計為會限制動態記憶體分配(dynamic memory allocation),讓手機平台上可以擁有最佳化的效能。 可以使用Query 和Q (Q
是Query<T>.First()
的縮寫)這兩個extension method來使用UQuery。
Q
與Query
實際上是使用UQueryBuilder 來建構一個query,這些extension method可以減少在建立UQueryBuilder
時需要撰寫的模板程式碼。
在使用UQuery之前,你必須要先載入並實體化UXML
,然後才能用Q
或Query
建立選取規則(selection rules)
可以透過element的name ,USS class ,element type (C# type) 來找到想要的element。
也可以使用predicate 或是組合[複雜結構的query](#Complex hierarchical queries)來找到想要的element
UQuery會在初始化時Cache這些選出來的Elements。
UI Toolkit不會自行銷毀沒用到的visual elements,它是使用C# garbage collector 來處理,因此最好不要在UIDocuments或Window之外建立這些elements的引用,避免讓C# garbage collector無法回收。
以下使用一個UXML來說明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <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 >
Query by name 語法為: Query(name: "element-name")
或是 Q(name: "element-name")
;你也可以省略參數名稱name
,直接使用Query("element-name")
1 2 List<VisualElement> result = root.Query("OK" ).ToList();
1 2 3 4 VisualElement result = root.Query("OK" ).First(); VisualElement result = root.Q("OK" );
1 2 VisualElement result3 = root.Query("OK" ).AtIndex(1 );
1 2 VisualElement result4 = root.Query("OK" ).Last();
Query by USS class 語法為:Query(className: "class-name")
或是 Q(className: "class-name")
1 2 List<VisualElement> result = root.Query(className: "yellow" ).ToList();
1 2 VisualElement result = root.Q(className: "yellow" );
Query by element type 語法為:Query<Type>()
或是 Q<Type>()
注意 :你只能使用actual type來選出Element,而不能使用base type。
1 2 3 4 VisualElement result = root.Q<Button>(); result.tooltip = "This is a tooltip!" ;
1 2 // 這句會選出第三個Button element VisualElement result = root.Query<Button>().AtIndex(2);
Query with a predicate 除了可以使用name
,class-name
,type
來選出element以外,還可以搭配Where
做更進一步的篩選,Where
的參數是一個VisualElement
。
1 2 List<VisualElement> result = root.Query(className: "yellow" ).Where(elem => elem.tooltip == "" ).ToList();
Complex hierarchical queries 可以將name
,class-name
,type
等組合在一起,做更複雜的選擇。
1 2 VisualElement result = root.Query<Button>(className: "yellow" , name: "OK" ).First();
1 2 VisualElement result = root.Query<VisualElement>("container2" ).Children<Button>("Cancel" ).First();