Search Unity

Code/Inspector Pattern for adapting UI window selectables to specific object

Discussion in 'UGUI & TextMesh Pro' started by Bamfax, Mar 20, 2019.

  1. Bamfax

    Bamfax

    Joined:
    Jun 12, 2016
    Posts:
    52
    Hi Everyone,

    I am looking for a pattern (code and inspector / editor serialization) which allows to retarget prebuilt UI windows (their selectables, be it toggles, sliders, buttons, dropdowns) to a specific, e.g. currently selected object. For example let's say the windows are targeting a car, allowing its customization (toggle motor running, dropdown for color, slider for horsepower) via UnityEvents of the window selectables. Now if there are multiple cars, and I need to retarget the selectables to the currently selected car, what would be the easiest/leanest pattern (in terms of code and how I would design the class inspector) to proxy the selectables (their UnityEvent/UnityActions) to the specific selected car?

    Other things to do in that regard:
    When selected car changes:
    - Toggle interactivity of selectable on / off
    - Reset selectable value to value of newly selected car

    Two styles came to my mind. Both do not appear yet ideal to me:
    a) Populate the UnityAction of the Selectables via AddListener. This is what I currently have. An Event is thrown when a different car is selected. A "CarToWindowLinker" class then retargets the non-persistent listeners of toggles, sliders, etc. This linking of the car method to its UnityAction is mostly hardcoded, which does not really appeal. It would be nice to be more generic and offering an inspector for "car color is accessed with this method, respective UI selectable is this dropdown", allowing to generically built a linker class in the inspector. Challenge here for me is the serialization: How do I serialize the different types of UnityActions? How do I serialize a method of a car only instantiated at runtime and put its delegate on the UnityAction? And it would also be challenging to adapt to allow multi-selects and still keep the oversight which non-persistent listeners are where.
    b) Provide a singleton of "always there" car methods, which are statically targeted by the windows using persistent listeners. The singleton then receives the currently selected car. Value changes of UI selectables are proxied through to the targeted car. The singleton would also need to take of en-/disabling interactivity of selectables and put a new value in them, once a different car is selected.

    The latter option currently looks easier to implement for me, also in terms of being an easier to understand concept. As often, the first thought "let's pop up these prebuilt windows over a selected car" was a little optimistic.

    Happy to hear if you would have better ideas or optimizations of the above.