Hi, I can’t seem to find the resources I need, all tutorials go around creating a view by script or having a finished view and accessing its VisualElements. But what we often need to do, is have an empty shell like a scroll view and instantiate a ton of prefabs in there that all have their own script and can act on their own.
This is exactly what I need to replicate with UI Toolkit.
What we would do in normal Unity UGUI is this:
[SerializeField] private Product productTemplate;
[SerializeField] private RectTransform scrollViewContent;
public void SpawnTemplates(int amount)
{
foreach (int i = 0; i < amount; i++)
Instantiate(productTemplate, scrollViewContent);
}
pretty easy and straight forward. We have our template (the productTemplate as a Prefab) and then just spam it into a UI element. The Product script is already attached and can do stuff on its own on every individual instance.
So what is the equivalent for UI Elements? I already created my ProductTemplate.uxml to spawn in, and I can already do that:
[MenuItem("Window/UI Toolkit/MyEditor")]
public static void ShowExample()
{
MyEditorWindow wnd = GetWindow<MyEditorWindow>();
wnd.titleContent = new GUIContent("MyEditor");
}
public void CreateGUI()
{
VisualElement root = rootVisualElement;
VisualTreeAsset uiAsset = TemplateFactory.ProductTemplate;
VisualElement ui = uiAsset.Instantiate();
root.Q("ProductList").Add(ui);
}
But how on earth to I add a script to these uxml elements?
I mean they are there, but they are basically useless. If I click their buttons, nothing will happen, they need a script that can handle their individual state somehow.
It would also be fine – even preferred – if the script is already attached somehow, so that every ProductTemplate.uxml automatically comes with the correct behavior. I find a lot on how to manipulate VisualElements via code, but I can’t find a way to give a layout its own script by default. Hope someone can guide me in the right direction!
Best,
Noblauch