Hello again. Im still trying to learn UI Elements. At the moment, I have the following problem.
An custom editor built on UI Elements does not allow me to dynamically change content in the editor. For an example, I created a similar solution on imgui in which I carry out similar manipulations. Namely, loading a texture with a background image by loading it using a formatted string. When adding a prefix, the texture with the desired index is loaded. In imgui everything works instantly, but not in uie
this is my code, for example. How i can fix it? Ho to force update/repaint ui?
UIElements is a retained mode UI system therefore you’ll have to handle events yourself to update the UI state.
In this specific example, this means that you need to listen for changes on the IntField and and change the image reference.
This should to the trick:
[CustomEditor(typeof(monoOverride))]
public class img_testing : Editor
{
Texture2D texture, none;
int index;
public override VisualElement CreateInspectorGUI()
{
texture = AssetDatabase.LoadAssetAtPath<Texture2D>($"Assets/Models/Resources/icon{index}.png");
none = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Models/Resources/none.png");
var root = new VisualElement();
var lbl = new Label();
var img = new Image ();
img.scaleMode = ScaleMode.ScaleToFit;
if (texture != null)
{
lbl.text = $"texture {texture.name} is load";
img.image = texture;
}
else
{
lbl.text = "Nothing is loaded";
img.image = none;
}
root.Add(img);
root.Add(lbl);
var intField = new IntegerField();
// Update image when IntField changes
intField.RegisterValueChangedCallback(evt => {
index = evt.newValue;
texture = AssetDatabase.LoadAssetAtPath<Texture2D>($"Assets/Models/Resources/icon{index}.png");
lbl.text = $"texture {texture.name} is loaded";
img.image = texture;
});
index = intField.value;
root.Add(intField);
return root;
}
}
Of course this introduces some duplication so it probably makes sense to create a method to initialize a texture from an index.