Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Question Accessing children in custom c# element

Discussion in 'UI Toolkit' started by Viroz_, Nov 25, 2023.

  1. Viroz_

    Viroz_

    Joined:
    Dec 30, 2022
    Posts:
    17
    I have created my custom VisualElement(code below) and I want to bind events to my buttons that I add directly into my UXML document, like following:
    upload_2023-11-25_18-11-37.png

    is there any way to access those buttons in that script?

    Code (CSharp):
    1. public class MenuWithIndicator : VisualElement
    2. {
    3.     public new class UxmlFactory : UxmlFactory<MenuWithIndicator, UxmlTraits> { }
    4.  
    5.     private List<Button> m_Buttons;
    6.     private VisualElement m_Indicator;
    7.  
    8.     public MenuWithIndicator()
    9.     {
    10.         AppendIndicator();
    11.  
    12.         // buttons don't exist yet
    13.     }
    14.  
    15.     // temporary solution
    16.     public void BindButtonEvents()
    17.     {
    18.         m_Buttons = Children().OfType<Button>().ToList();
    19.         foreach (Button button in m_Buttons)
    20.         {
    21.             button.RegisterCallback<PointerEnterEvent>((e) => { OnButtonHover(e.target as Button); });
    22.         }
    23.     }
    24.  
    25.     private void AppendIndicator()
    26.     {
    27.         m_Indicator = new VisualElement()
    28.         {
    29.             name = "Indicator",
    30.             style =
    31.             {
    32.                 height = 20,
    33.                 width = 2,
    34.                 backgroundColor = Color.white,
    35.                 position = Position.Absolute,
    36.                 marginLeft = 5
    37.             }
    38.         };
    39.  
    40.         Add(m_Indicator);
    41.     }
    42.  
    43.     private void OnButtonHover(Button button)
    44.     {
    45.         if (m_Indicator == null)
    46.             return;
    47.  
    48.         m_Indicator.style.top = button.layout.yMin;
    49.     }
    50. }
    51.  
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    8,647
    Register a
    AttachToPanelEvent
    callback in your constructor and do the initialisation there.
     
    Viroz_ likes this.
  3. Viroz_

    Viroz_

    Joined:
    Dec 30, 2022
    Posts:
    17
    Thanks, works fine.