Search Unity

Dynamically set the state of UIElements according to some state ?

Discussion in 'UIElements' started by aybe, Dec 18, 2018.

  1. aybe

    aybe

    Joined:
    May 24, 2015
    Posts:
    104
    As I needed to dynamically enable/disable elements of my UI according to some state, e.g button X shall be enabled only if Y == Z; I ended up writing the following which works surprisingly well:

    Code (CSharp):
    1. scheduler
    2. .Execute(s => _baseDirectoryBrowseButton.SetEnabled(HasMaterial))
    3. .Forever();
    Code (CSharp):
    1. using System;
    2. using JetBrains.Annotations;
    3.  
    4. // ReSharper disable once CheckNamespace
    5. namespace UnityEngine.UIElements
    6. {
    7.     // ReSharper disable once InconsistentNaming
    8.     public static class IVisualElementScheduledItemExtensions
    9.     {
    10.         /// <summary>
    11.         ///     Repeats this action forever.
    12.         /// </summary>
    13.         /// <param name="item"></param>
    14.         /// <returns></returns>
    15.         /// <exception cref="ArgumentNullException"></exception>
    16.         public static IVisualElementScheduledItem Forever([NotNull] this IVisualElementScheduledItem item)
    17.         {
    18.             if (item == null)
    19.                 throw new ArgumentNullException(nameof(item));
    20.  
    21.             return item.Until(() => false);
    22.         }
    23.     }
    24. }
    So this is a pseudo-mix of INotifyPropertyChanged and binding which just works but I'm not sure about the performance if used heavily.

    Any thoughts ?
     
  2. antoine-unity

    antoine-unity

    Unity Technologies

    Joined:
    Sep 10, 2015
    Posts:
    102
    Polling is not a bad way to implement change tracking. If there are many small schedule items, the scheduler will also make sure to not exceed a certain budget (currently hard coded to 20ms) and will continue execution during the next frame.

    But there is no magic going on and if one scheduled item is very expensive there is nothing the system can do against that.

    If you can leverage any other event/callback/etc. that is specific to your problem and only then update visual elements, it is guaranteed to give the best performance.
     
  3. aybe

    aybe

    Joined:
    May 24, 2015
    Posts:
    104
    Alright, I'll just continue that way until it blows up :D
     
    Devi-User likes this.