Hard Coding Strings: Fragility

So I’m liking UI Toolkit so far, but I did want to point out a couple things that are very fragile about some of the approaches in my book.

StyleSheet styleAsset = AssetDatabase.LoadAssetAtPath<StyleSheet>(path + "TaskListEditor.uss");
savedTasksObjectField = container.Q<ObjectField>("savedTasksObjectField");

Essentially hard coded strings. Very fragile; any changes to the path or those names breaks stuff. I found a solution to the path that I haven’t had issues with so far and can live with I think, so here’s that- the default settings for scripts in Unity.

[SerializeField] private VisualTreeAsset uxmlAsset = default;
[SerializeField] private StyleSheet styleAsset = default;

TaskWindow

Global variables for the whole editor window script.
I haven’t found a good solution to the string queries for uxml items, any ideas?

2 Likes

A good tip.

I’m not aware of a way to avoid string queries for items, but this is a good place to define string constants.

Just to close the loop on this for others, once you have a reference to the VisualTreeElement through the SerializedField value, you just call Instantiate() on it to get a VisualElement to add to the rootVisualElement, same as if you had loaded it through the AssetDatabase.LoadAssetAtPath() method, e.g.,

this.rootVisualElement.Add(this.uxmlAsset.Instantiate());
1 Like

Privacy & Terms