Skip to content

t1k:unity:base:messagepipe

FieldValue
Modulebase
Version5.116.6
Effortlow
Tools—

Keywords: event, messagepipe, publisher, pubsub, signal, signalbus, subscriber, vcontainer

/t1k:unity:base:messagepipe

MessagePipe Signals — Unity + VContainer

Section titled “MessagePipe Signals — Unity + VContainer”

Pub/sub messaging via MessagePipe 1.8.1 + MessagePipe.VContainer. Signals are the decoupling seam between systems: a publisher never references its subscribers.

  1. Every signal is a public readonly struct — never a class, never a record. Zero-alloc publish.
  2. Empty signals publish with .Publish(default) — never new XSignal().
  3. Inject IPublisher<T> / ISubscriber<T> — never the obsolete SignalBus.
  4. Every Subscribe returns an IDisposable — collect it and dispose it. Leaked subscriptions fire on recycled/destroyed objects.

One readonly struct per event. readonly fields (or get-only properties) + a constructor. XML-doc the type and every field — a signal is a public contract read by systems that never see each other.

#nullable enable
namespace Arrow3D.Gameplay.Signals
{
/// <summary>Fired when an arrow takes damage from a hazard or collision.</summary>
public readonly struct ArrowDamagedSignal
{
/// <summary>The arrow that was damaged.</summary>
public readonly Arrow arrow;
public ArrowDamagedSignal(Arrow arrow)
{
this.arrow = arrow;
}
}
}

Empty (payload-free) signal — the whole body is { }:

/// <summary>Fired at the start of the level intro so tiles can animate in lockstep.</summary>
public readonly struct LevelIntroStartedSignal { }

Naming: <Event>Signal (ArrowDamagedSignal, LevelIntroStartedSignal) or On<Event>Signal for feature/UI signals (OnWallpaperUnlockedSignal). Past tense for facts that already happened; Request/Dismiss suffixes for commands.

File layout: one signal per file under .../Signals/<Name>Signal.cs, or group a feature’s signals in <Feature>Signals.cs (see WallpaperCollectionSignals.cs). Use internal when the signal never crosses an assembly boundary.

private IPublisher<ArrowDamagedSignal> arrowDamagedPublisher = null!;
private IPublisher<NoMovesAvailableSignal> noMovesPublisher = null!;
// payload signal — construct it
this.arrowDamagedPublisher.Publish(new ArrowDamagedSignal(arrow));
this.arrowDamagedPublisher.Publish(new(arrow)); // target-typed new is fine
// EMPTY signal — always `default`
this.noMovesPublisher.Publish(default);

Publish(default) on an empty struct is the canonical form: it is the zero value of a type with no fields, so it allocates and initializes nothing. new NoMovesAvailableSignal() is the same value but noisier, and it invites someone to later add a field with no constructor to set it.

Subscribe returns an IDisposable. Batch them into a DisposableBag and dispose the built bag on teardown.

using MessagePipe;
private IDisposable? subscriptions;
void IInitializable.Initialize()
{
var bag = DisposableBag.CreateBuilder();
this.collectedSubscriber.Subscribe(this.OnCollected).AddTo(bag);
this.updateCurrencySubscriber.Subscribe(this.OnUpdateCurrency).AddTo(bag);
this.subscriptions = bag.Build();
}
void IDisposable.Dispose()
{
this.subscriptions?.Dispose();
this.subscriptions = null;
}

Handler signature is always Action<TSignal> — even for empty signals, where the parameter is discarded: subscriber.Subscribe(_ => this.Refresh()).

For a one-shot await inside a scope, using var is enough:

using var __ = this.collectedSubscriber.Subscribe(_ => tcs.TrySetResult());

Dispose site by owner type:

OwnerSubscribe inDispose in
DI service (IInitializable)Initialize()Dispose()
Pooled entity / tileOnSpawn()OnRecycle()
Plain MonoBehaviourOnEnable()OnDisable() / OnDestroy()

Services — constructor injection (preferred; MainGame layer requires DI, no service locator):

public DailyMissionService(
ISubscriber<CollectedSignal> collectedSubscriber,
ISubscriber<RewardedAdCompletedSignal> rewardedAdCompletedSubscriber)
{
this.collectedSubscriber = collectedSubscriber;
this.rewardedAdCompletedSubscriber = rewardedAdCompletedSubscriber;
}

Pooled entities / MonoBehaviours — container resolve once at instantiate, not per spawn:

protected override void OnInstantiate()
{
base.OnInstantiate();
this.levelIntroStartedSubscriber = this.Container.Resolve<ISubscriber<LevelIntroStartedSignal>>();
}

builder.RegisterMessagePipe() runs once at the root scope (via GameFoundationVContainer.RegisterGameFoundation → RegisterSignalBus). It registers open generics, so IPublisher<T> / ISubscriber<T> resolve for any T with no per-signal registration.

Do not add RegisterMessageBroker<MySignal>() or a second RegisterMessagePipe() in a feature or child scope — a second broker registration splits the bus so publishers and subscribers stop seeing each other. Child scopes (PuppyGoVContainer, PuzzleGameVContainer) inherit the root broker, which is what makes cross-scope signals work.

GameFoundation.Signals.SignalBus (Fire<T>() / Subscribe<T>(Action)) is [Obsolete] — a thin wrapper that resolves IPublisher<T> and calls Publish(default) for you. New code injects IPublisher<T> / ISubscriber<T> directly. Migration map:

ObsoleteReplacement
signalBus.Fire<XSignal>()xPublisher.Publish(default)
signalBus.Fire(new XSignal(a))xPublisher.Publish(new XSignal(a))
signalBus.Subscribe<XSignal>(OnX)xSubscriber.Subscribe(OnX).AddTo(bag)
signalBus.Unsubscribe<XSignal>(OnX)subscriptions.Dispose()

Touching a file that still uses SignalBus? Migrate that file’s usages — don’t add new ones.

  • Empty struct + new — Publish(new XSignal()) compiles and works, but Publish(default) is the house form. Consistency matters here because the empty-struct case is the one people copy.
  • class signal = per-publish heap allocation. In per-frame or per-collision publish paths that is GC pressure the profiler will find later. readonly struct is not optional.
  • Mutable struct fields silently do nothing useful — subscribers receive a copy. readonly on both the struct and its fields makes that explicit instead of a bug.
  • Dropped IDisposable — subscriber.Subscribe(handler); with the result discarded is a leak. On a pooled tile the handler keeps firing after OnRecycle and touches a recycled object.
  • IL2CPP stripping — MessagePipe and MessagePipe.VContainer are already preserve="all" in Assets/Scripts/link.xml. If a new assembly holds only signal types and gets stripped, add it there.
  • Resolving in OnSpawn re-resolves on every pool spawn. Resolve in OnInstantiate (once per instance), subscribe in OnSpawn.
  • No async/request handlers in this project. IAsyncPublisher<T> and IRequestHandler<T,R> exist in MessagePipe but are unused here — don’t introduce them without a concrete need; the sync bus keeps ordering easy to reason about.
  1. public readonly struct <Name>Signal in the feature’s Signals/ folder, XML-documented.
  2. No payload → body is { }; payload → readonly fields + constructor.
  3. Publisher: inject IPublisher<T>, call Publish(default) (empty) or Publish(new T(...)).
  4. Subscriber: inject ISubscriber<T>, Subscribe(handler).AddTo(bag), dispose the bag on teardown.
  5. Zero registration code — the root RegisterMessagePipe() already covers it.