Skip to content

AlexVertax/Value-Observer

Repository files navigation

Value Observer

Value Observer is an editor-friendly implementation of the Observer pattern for Unity.

It helps you react to value changes without wiring custom boilerplate every time. The package includes serializable observers, links to fields and properties, links to other observers, and linked method calls, all designed to work comfortably in the Unity Inspector.

Features

  • ValueObserver<T> for observable values with change events
  • Inspector-friendly listeners based on UnityEvent
  • Optional value validation before applying changes
  • LinkedObserver<T> to work with an observer stored on another component
  • LinkedValue<T> to link directly to a field or property
  • LinkedMethod<...> to invoke methods through serialized links
  • Dynamic runtime API in addition to Inspector setup
  • Example scene and example scripts included

Main Types

ValueObserver<T>

Use it when you want a value that notifies listeners when it changes.

using InfinityCode.Observers;

public ValueObserver<int> health = new ValueObserver<int>(100);

private void Start()
{
    health += OnHealthChanged;
    health.AddValidation(ValidateHealth);
}

private void OnHealthChanged(int value)
{
    UnityEngine.Debug.Log($"Health: {value}");
}

private void ValidateHealth(Validatable<int> value)
{
    value.Value = UnityEngine.Mathf.Clamp(value, 0, 100);
}

LinkedObserver<T>

Use it when you need to access another ValueObserver<T> through a serialized link.

public LinkedObserver<int> playerHealth;

private void Start()
{
    playerHealth += OnHealthChanged;
    int currentHealth = playerHealth;
}

LinkedValue<T>

Use it to link a field or property on a target object and read or write it through a typed wrapper.

public LinkedValue<UnityEngine.Vector3> cameraPosition;

public void MoveUp()
{
    cameraPosition.Value += UnityEngine.Vector3.up;
}

LinkedValue<T> can also observe changes with StartObserving(...) or manual checks through IsChanged.

LinkedMethod<...>

Use it to serialize a reference to a method and invoke it later.

public LinkedMethod<int, string> getPlayerName;
public LinkedMethod<int> getPlayerCount;

public void PrintRandomPlayer()
{
    int count = getPlayerCount.Invoke();
    string name = getPlayerName.Invoke(UnityEngine.Random.Range(0, count));
    UnityEngine.Debug.Log(name);
}

Documentation

Support

About

Value Observer is an editor-friendly implementation of the Observer pattern for Unity

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages