Skip to content

Toggle Controllers

Daniel Colina edited this page Jul 15, 2020 · 11 revisions

Overview

Toggle controllers are specialized entity controllers that control a UIToggle component.

The base implementation of a toggle controller is AToggleController<TToggleProperties>. It inherits from AEntityController<TEntityProperties>, and as such maintains all behaviour detailed in entity controllers.

AToggleController<TToggleProperties> exposes a few methods that sub-classes can override:

  • virtual HandleValueChanged(bool value): Handler for backend behaviour (passing data, sending out events, etc) when toggled.
  • virtual AnimateValueChanged(bool value): Handler for frontend behaviour (setting animator values) when toggled.
  • virtual HandleInteractabilityChanged(bool value): Handler for backend behaviour when interactability has been changed.
  • virtual AnimateInteractabilityChanged(bool value): Handler for frontend behaviour when interactability has been changed.

In addition, AToggleController<TToggleProperties> exposes a few public methods:

  • ToggleInteractability(bool value): Toggles interactability on controlled UIToggle component to the given value.
  • ToggleInternal(bool value): Toggles controlled UIToggle to the given value, but prevents backend callbacks from being dispatched.

Examples

For an example, see the ExampleToggleController below:

Example Toggle Controller

// This is a simple toggle controller that stores a string as its properties.
public class ExampleToggleController : AToggleController<string>
{
    [SerializeField] private TextMeshProUGUI label;
    [SerializeField] private Animator anim;
    
    protected override void OnPropertiesSet()
    {
        label.text = Properties;
    }    

    protected override void HandleValueChanged(bool value)
    {
        // Handle backend behaviour like dispatching a global
        // message to other scripts here.
        base.HandleValueChanged(value);
        Debug.Log($"My key is {Properties.key}, and I was changed to {value}!");
    }

    protected override void AnimateValueChanged(bool value)
    {
        // In most cases, DoozyUI can manage visual behaviour,
        // but in the case that a toggle controller needs to change
        // visually when toggled in a format that is not supported
        // by DoozyUI, manage doing it here.
        base.AnimateOnClick();
        anim.SetBool("Toggled", value);
    }

    protected override void AnimateInteractabilityChanged(bool value)
    {
        // As with AnimateValueChanged, DoozyUI can usually manage visual
        // behaviour, but in the case that a toggle controller needs to
        // change visually when interactability is enabled or disabled
        // that is not supported by DoozyUI, manage doing it here.
        base.AnimateInteractabilityChanged();
        anim.SetBool("Interactable", value);
    }
}