Out of desire for cleaner UXML, I got it into my head that I’d like to reference item templates in the same manner one references UXML templates. However, it appears that VisualTreeAsset hides alias info, for whatever reason.
Is there a way to look up template alias information found in the UXML without the following Editor-only hack?
private static bool TryResolveItemTemplateFromId(in VisualElement self, in string aliasId, out VisualTreeAsset template)
{
template = null;
#if UNITY_EDITOR
var pairs = self
.Ancestors() // My own extension
.Where(ancestor => ancestor.visualTreeAssetSource != null)
.Select(ancestor => new UnityEditor.SerializedObject(ancestor.visualTreeAssetSource))
.Select(so => so.FindProperty("m_Usings"))
.SelectMany(usings =>
{
var list = new List<UnityEditor.SerializedProperty>();
for (int i = 0; i < usings.arraySize; i++)
list.Add(usings.GetArrayElementAtIndex(i));
return list;
}).Select(usingEntry => KeyValuePair.Create(
usingEntry.FindPropertyRelative("alias").stringValue,
usingEntry.FindPropertyRelative("asset").objectReferenceValue as VisualTreeAsset));
foreach (var pair in pairs)
{
if (pair.Key.Equals(aliasId))
{
template = pair.Value;
return true;
}
}
#endif
return false;
}