Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Slider with variable bounds

Discussion in 'UI Toolkit' started by SkandYxyz, Mar 16, 2023.

  1. SkandYxyz

    SkandYxyz

    Joined:
    Mar 13, 2015
    Posts:
    83
    Hi,

    how can I adjust the high and low values of a slider created with ui builder and used in a custom script inspector window when the user changes variables and onvalidate is called? Do I have to create my own derived slider? Can i bind more than one serialized variable to a custom ui element?

    Kind regards
     
  2. SkandYxyz

    SkandYxyz

    Joined:
    Mar 13, 2015
    Posts:
    83
    It's actually dead simple if you know how it's done.

    Code (CSharp):
    1.     [CustomEditor(typeof(TimeOfDay))]
    2.     public class TimeOfDayEditor : Editor
    3.     {
    4.         public VisualTreeAsset m_InspectorXML;
    5.         TimeOfDay myTarget;
    6.         Slider Day;
    7.         IntegerField DaysPerYear;
    8.  
    9.         public override VisualElement CreateInspectorGUI()
    10.         {
    11.             // Get target instance
    12.             myTarget = (TimeOfDay)target;
    13.  
    14.             // Create a new VisualElement to be the root of our inspector UI
    15.             VisualElement myInspector = new VisualElement();
    16.  
    17.             // Load and clone a visual tree from UXML
    18.             m_InspectorXML.CloneTree(myInspector);
    19.  
    20.             // Query Slider #Day
    21.             Day = myInspector.Query<Slider>("Day");
    22.  
    23.             // Set highvalue
    24.             Day.highValue = myTarget.DaysPerYear;
    25.  
    26.             // Query IntegerField #DaysPerYear
    27.             DaysPerYear = myInspector.Query<IntegerField>("DaysPerYear");
    28.  
    29.             // Register value changed event
    30.             DaysPerYear.RegisterValueChangedCallback<int>(OnDaysPerYearChanged);
    31.  
    32.             // Return the finished inspector UI
    33.             return myInspector;
    34.         }
    35.  
    36.         private void OnDaysPerYearChanged(ChangeEvent<int> evt)
    37.         {
    38.             // Set Day Sliders high value
    39.             Day.highValue = evt.newValue;
    40.         }
    41.  
    42.     }