I have a question about the best approach to templates, and using them.
Let’s say we have a template for a button/panel that has an icon and text. And when using this template we want to change the icon sprite and text for each panel. What is the best approach to do it?
For icons, we can create styles and override it, but not for text.
We can create custom controls that will store both and set them (similar to default UI Toolkit button) but I’m struggling with when should I search for specific elements and set them. In on Geometry Changed?
I have something like that but I don’t know if it is the best aproach.
namespace LoopGame.UI
{
using SoBadSoGoodGames.UI;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.UIElements;
[UxmlElement]
public partial class BottomBarButton : CustomButton
{
private Sprite iconBackground;
private string localeKey;
private VisualElement buttonIconImage;
private Label buttonName;
[UxmlAttribute]
public Sprite IconBackground
{
get => iconBackground;
set
{
iconBackground = value;
UpdateButtonIcon();
}
}
[UxmlAttribute]
public string LocaleKey
{
get => localeKey;
set
{
localeKey = value;
UpdateButtonName();
}
}
public BottomBarButton()
{
RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
private void OnGeometryChanged(GeometryChangedEvent evt)
{
UpdateButtonIcon();
UpdateButtonName();
UnregisterCallback<GeometryChangedEvent>(OnGeometryChanged); // Remove callback after execution
}
private void UpdateButtonIcon()
{
buttonIconImage ??= this.Q<VisualElement>("Icon");
if (buttonIconImage != null)
{
buttonIconImage.style.backgroundImage = new StyleBackground(IconBackground);
}
}
private void UpdateButtonName()
{
buttonName ??= this.Q<Label>("NameLabel");
if (buttonName?.GetBinding(nameof(Label.text)) is LocalizedString localizedString)
localizedString.TableEntryReference = LocaleKey;
}
}
}