Skip to content

Entity Controllers

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

Overview

Entity controllers serve as the foundation for the entire framework. At their core, they are specialized MonoBehaviours that hold properties.

The base implementation of an entity controller is AEntityController<TEntityProperties>.

AEntityController<TEntityProperties> exposes a few methods that sub-classes can easily override, listed below:

  • virtual AddListeners(): Handler for adding listeners to events. Called by OnEnable() by default.
  • virtual RemoveListeners(): Handler for removing listeners to events. Called by OnDisable() by default.
  • virtual OnPropertiesSet(): Handler for initializing controller once properties have been set. Called by SetProperties(TEntityProperties properties) by default.

In addition, AEntityController<TEntityProperties> exposes a public method:

  • SetProperties(TEntityProperties properties): Sets the properties of the entity to the given properties. This triggers the OnPropertiesSet() method when finished.

Because of their high level of abstraction, entity controllers can be declared that inherit from AEntityController<TEntityProperties> to control any entity that needs to contain properties, from UI controllers like button controllers and toggle controllers to camera controllers, to any entity that makes use of specific variable set of properties.

Examples

For an example, see the ExampleEntityController below:

Example Entity Controller

// A simple delegate that passes an integer.
public static Action<int> ExampleEvent;

// This is a simple entity controller that stores an integer as its properties.
public class ExampleEntityController : AEntityController<int>
{
    protected override void AddListeners()
    {
        // Add event listeners here.
        base.AddListeners();
        ExampleEvent += ExampleEventHandler;
    }

    protected override void RemoveListeners()
    {
        // Remove event listeners here.
        base.RemoveListeners();
        ExampleEvent -= ExampleEventHandler;
    }

    private void ExampleEventHandler(int value)
    {
        // Set new properties based on the passed value.
        SetProperties(value);
    }

    protected override void OnPropertiesSet()
    {
        // Handle initializing this entity given its properties.
        base.OnPropertiesSet();
        Debug.Log($"My value is: {Properties}");
    }
}