Skip to main content

Switcher Binders

The Switcher pattern: bool → one of two preset values.


Overview

A Switcher binder takes a bool and returns one of two values:

  • true_trueValue
  • false_falseValue

An alternative to converters for simple "if/else" cases.


SwitcherBinder<T>

The base class (not a MonoBehaviour):

public abstract class SwitcherBinder<T> : Binder, IBinder<bool>
{
// Serialized in the Inspector:
protected T _trueValue;
protected T _falseValue;

public void SetValue(bool value)
{
SetValue(value ? _trueValue : _falseValue);
}

protected abstract void SetValue(T value);
}

Modes: OneWay, OneTime. TwoWay and OneWayToSource are not supported.


Ready-made Switcher binders

Almost every standard binder has a Switcher variant:

Switcher binderPicks betweenExample
TextSwitcherBindertwo strings"Active" / "Inactive"
TextFontSwitcherBindertwo fontsBold / Regular
TextFontSizeSwitcherBindertwo sizes24 / 16
TextAlignmentSwitcherBindertwo alignmentsCenter / Left
ImageSpriteSwitcherBindertwo spritesCheckOn / CheckOff
ImageFillSwitcherBindertwo fillAmount values1.0 / 0.0
SliderMinMaxSwitcherBindertwo min/max pairs(0,100) / (0,10)
GraphicColorSwitcherBindertwo colorsGreen / Red
CanvasGroupAlphaSwitcherBindertwo alpha values1.0 / 0.3
RendererMaterialsColorSwitcherBindertwo colorsLit / Dark
SelectableColorBlockSwitcherBindertwo ColorBlocksNormal / Disabled

SwitcherMonoBinder

The MonoBehaviour variant for the Inspector:

// Three generic overloads:
SwitcherMonoBinder<T> // no converter
SwitcherMonoBinder<T, TTarget> // with a target component
SwitcherMonoBinder<T, TTarget, TConv> // with a converter

Example

ViewModel

[ViewModel]
public partial class TaskViewModel
{
[OneWayBind] private bool _isCompleted;
}

Inspector

  1. Add TextSwitcherBinder to the object with TextMeshPro
  2. Set:
    • True Value = "Done"
    • False Value = "In progress"
  3. Bind to IsCompleted

Result: the text switches whenever IsCompleted changes.

Status colors

  1. Add GraphicColorSwitcherBinder
  2. True Value = green
  3. False Value = red

Switcher vs converter

SwitcherConverter
Two fixed valuesArbitrary transformation
Configured in the InspectorLogic in code
bool input onlyAny input type
Quick setupReusable logic

See also