Search Unity

Custom inspector built with UIBuilder. How to hook up buttons?

Discussion in 'UIElements' started by jwvanderbeck, Dec 24, 2019.

  1. jwvanderbeck

    jwvanderbeck

    Joined:
    Dec 4, 2014
    Posts:
    702
    So this post is kind of two fold.

    First from a user standpoint, I feel there is a large piece missing from UI Builder. In uGUI you could wire up your events directly in the inspector. Shouldn't this functionality also exist in UIBuilder? Or is the underlying system so different that this isn't practical?

    Which leads to the second point, trying to understand HOW the underlying system works. I have made a simple inspector using UI Builder. It has some property fields and a couple buttons for now. Nothing amazing. Now I want to hook those buttons up to do something. I can't seem to figure it out though. I tried some code that seems like it should work based on the docs, but doesn't appear to do anything. It doesn't error, or throw any warnings, it just does nothing when I click on the button.

    Code (CSharp):
    1.     [CustomEditor(typeof(Poisson))]
    2.     public class PoissonEditor : UnityEditor.Editor
    3.     {
    4.         public override VisualElement CreateInspectorGUI()
    5.         {
    6.             var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/PoissonInspector.uxml");
    7.             var root = visualTree.CloneTree();
    8.             root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/PoissonInspector.uss"));
    9.            
    10.             root.Query<Button>("sample").First().RegisterCallback<MouseDownEvent>(SamplePoints);
    11.             return root;
    12.         }
    13.  
    14.         private void SamplePoints(MouseDownEvent evt)
    15.         {
    16.             Debug.Log("Mouse Down");
    17.             Poisson p = target as Poisson;
    18.  
    19.             if (p != null)
    20.             {
    21.                 p.CreatePoints();
    22.             }
    23.         }
    24.     }
    25.  
    For reference here is the super basic uxml as well:

    Code (CSharp):
    1. <ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements">
    2.     <ui:VisualElement style="flex-grow: 1;">
    3.         <Style src="PoissonInspector.uss" />
    4.         <uie:PropertyField name="density" view-data-key="density" binding-path="density" label="Point Density" />
    5.         <uie:PropertyField name="minRadius" binding-path="minRadius" label="Minimum Point Radius" />
    6.         <uie:PropertyField name="maxRadius" binding-path="maxRadius" label="Maximum Point Radius" />
    7.         <uie:PropertyField name="size" binding-path="size" label="Area" />
    8.         <uie:PropertyField name="prefab" binding-path="prefab" label="Prefab to Spawn" />
    9.         <uie:PropertyField name="image" binding-path="image" label="Image Influence" />
    10.         <ui:Button text="Generate Points" name="sample" binding-path="sample-points" />
    11.     </ui:VisualElement>
    12. </ui:UXML>
     
  2. jwvanderbeck

    jwvanderbeck

    Joined:
    Dec 4, 2014
    Posts:
    702
    So it turns out that for whatever super confusing reason button events are handled differently than how the docs show events are done. The following code works:

    Code (CSharp):
    1.     [CustomEditor(typeof(Poisson))]
    2.     public class PoissonEditor : UnityEditor.Editor
    3.     {
    4.         public override VisualElement CreateInspectorGUI()
    5.         {
    6.             var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>("Assets/PoissonInspector.uxml");
    7.             var root = visualTree.CloneTree();
    8.             root.styleSheets.Add(AssetDatabase.LoadAssetAtPath<StyleSheet>("Assets/PoissonInspector.uss"));
    9.  
    10.             root.Query<Button>("sample").First().clicked += SamplePoints;
    11.             root.Query<Button>("clear").First().clicked += ClearPoints;
    12.             return root;
    13.         }
    14.  
    15.         private void ClearPoints()
    16.         {
    17.             Poisson p = target as Poisson;
    18.  
    19.             if (p != null)
    20.             {
    21.                 p.Clear();
    22.             }
    23.         }
    24.  
    25.         private void SamplePoints()
    26.         {
    27.             Poisson p = target as Poisson;
    28.  
    29.             if (p != null)
    30.             {
    31.                 p.CreatePoints();
    32.             }
    33.         }
    34.     }
    35.  
     
  3. BubbaRichard

    BubbaRichard

    Joined:
    Jul 1, 2012
    Posts:
    38
    but it does allow more options for instances
    toggle.RegisterCallback<ChangeEvent<bool>>(x =>
    {
    Method0(some key);
    Method1(some other value);
    };


    but you have to watch yourself with this, if you assign the value in a loop, it will be the last value of the loop (if a for int loop then the last value + 1) when adding button manual using the style or itinerating through the tree.

    for (int n = 0; n < list.Length; ++n)
    {
    Button btn = new Button() {text = "something"};
    btn.clickable.clicked += () =>
    {
    Debug.Log(n);
    }
    }

    if the list is 2 long then it will always print 2 (the last value + 1)
    so you will have to code it like this
    for (int n = 0; n < list.Length; ++n)
    {
    Button btn = new Button() {text = "something"};
    btn.clickable.clicked += () =>
    {
    int j = n;
    Debug.Log(j);
    }
    }
     
  4. vestigial

    vestigial

    Joined:
    May 9, 2015
    Posts:
    121
    I ran into exactly this problem too. Surprisingly it works with right click though. Its frustrating to do something that should be simple (changing MouseUp to MouseDown) and have it not work.
     
  5. jwvanderbeck

    jwvanderbeck

    Joined:
    Dec 4, 2014
    Posts:
    702
    What is frustrating to me is just the inconsistency. Why are some events one way and click events another, more complicated, way?
     
  6. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    97
    Hi, a built in ClickEvent will be available starting with 2020.1.
    This will make it possible to register a callback on elements like the rest of the API.
     
    jwvanderbeck likes this.
  7. TiagoAlvesPretia

    TiagoAlvesPretia

    Joined:
    Oct 4, 2017
    Posts:
    5
    On the same topic, the ability to hook up the callbacks through inspector (not through code) will be deprecated? :( Couldn't find any info anywhere regarding that.
     
  8. jwvanderbeck

    jwvanderbeck

    Joined:
    Dec 4, 2014
    Posts:
    702
    Yeah that part of my original post I think was lost in the shuffle, but would like to know if there are plans to allow editor side (design side) hook up of UI events like you can currently do with uGUI.
     
  9. jonathanma_unity

    jonathanma_unity

    Unity Technologies

    Joined:
    Jan 7, 2019
    Posts:
    97
    I wouldn't say deprecated is the right word, it might be different but it's hard to tell right now how it gonna ends up.
     
  10. benoitd_unity

    benoitd_unity

    Unity Technologies

    Joined:
    Jan 2, 2018
    Posts:
    133
    Could you please go a little over why this is important to you? Giving some context would also help: are you the one implementing the UI or setting up logic? The size of the team working on the project?
     
  11. uDamian

    uDamian

    Unity Technologies

    Joined:
    Dec 11, 2017
    Posts:
    489
    Just some context. One of the goals of UIElements was to be able to use plain source assets for the look and feel of your UI, separate from functionality.

    The UI look-and-feel assets (UXML and USS) are more like texture assets than ScriptableObject assets. You can load them at any time, from anywhere, and just paste them on the screen as many times (copies) as you want.

    When you want to attach some functionality, like make a Button call a function, you explicitly look for that Button in your current UI on screen and if you find it, you attach yourself to the correct events (not saying that current inconsistent way of doing this with
    .clickable.clicked = func
    is good, just the higher level query+events pattern). Whoever registered this callback should not care where the UI is, where it was loaded from, when it was loaded, nor where the Button is in the UI hierarchy.

    The UI Builder, in its initial form, will focus on creating the look and feel of the UI, not the logic. You can use the UI Builder to set up markers in the UI so the code can easily find specific functional elements (like give them a unique name), but the assets you create stay independent from the code.

    There are also performance benefits to keeping logic all in C# and away from string-based UXML files. Optimizations can be made to the code but if you reference functions in UXML, you have to rely on runtime-reflection every time you load these files.

    You also don't get help from your IDE when looking for where a function is being call and when you use automatic refactoring tools, they will not affect any references to your code in your UXML files.

    So while convenient, the uGUI Events/callback system has its problems - problems that we didn't want to bring into UIElements, as-is, for the reasons above.

    That said, we do want the UI creation process to be a good experience and I don't have trouble seeing why being able to simply assign a callback to a button is really nice. It is. And I think we should have this capability in the future. We just need to do it a bit differently, like having the UI Builder generate the event registration C# code for your (instead of just using reflection at runtime).
     
    vestigial likes this.
unityunity