Search Unity

Question Add buttons to the UI Builder inspector of a custom component.

Discussion in 'UI Toolkit' started by _geo__, Jun 1, 2023.

  1. _geo__

    _geo__

    Joined:
    Feb 26, 2014
    Posts:
    1,343
    Is it currently possible to add a button to the UI Builder inspector?
    I have a custom component and I would like a button to execute some actions on it.

    Right now I do some string trickery to make it look a little like a button:
    upload_2023-6-1_17-28-30.png

    Clicking on the "[ Restart Particles ]" triggers an action on my custom component. I do not care about the value of the checkbox at all. It's the best replacement for a button I have come up with so far but I am sure we can do better, no?

    Also, can we trigger the UNSET action via code on the inspector? I'd like to keep that white bar away from my fake buttons.

    upload_2023-6-1_17-31-51.png

    Thank you
     
    Aldeminor likes this.
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,930
    Right now I believe the answer is: not yet. But it is planned.
     
  3. _geo__

    _geo__

    Joined:
    Feb 26, 2014
    Posts:
    1,343
    I have found a way to "reset" the values with reflection, though it's ugly.

    Code (CSharp):
    1. public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
    2. {
    3.     base.Init(ve, bag, cc);
    4.  
    5.     // List<string> m_Properties in UXMLAsset (https://github.com/Unity-Technologies/UnityCsReference/blob/ddda763e79614c13cb63ec8b9dac375fd3be2b24/ModuleOverrides/com.unity.ui/Core/UXML/UxmlObjectAsset.cs)
    6.     var fieldInfo = bag.GetType().GetField("m_Properties", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
    7.     if (fieldInfo != null)
    8.     {
    9.         var fields = fieldInfo.GetValue(bag) as List<string>;
    10.         for (int i = 0; i < fields.Count-1; i++)
    11.         {
    12.             var field = fields[i];
    13.             string fieldLower = field.ToLower();
    14.             if (fieldLower.Contains("particles")) // <- filter the fields you need to reset.
    15.             {
    16.                 fields[i + 1] = "false"; // I know my field is a bool.
    17.             }
    18.         }
    19.     }
    20.  
    21.     // ...
    22.  
    23. }