t1k:unity:base:messagepipe
| Field | Value |
|---|---|
| Module | base |
| Version | 5.116.6 |
| Effort | low |
| Tools | — |
Keywords: event, messagepipe, publisher, pubsub, signal, signalbus, subscriber, vcontainer
How to invoke
Section titled “How to invoke”/t1k:unity:base:messagepipeMessagePipe 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.
Golden rules
Section titled “Golden rules”- Every signal is a
public readonly struct— never a class, never a record. Zero-alloc publish. - Empty signals publish with
.Publish(default)— nevernew XSignal(). - Inject
IPublisher<T>/ISubscriber<T>— never the obsoleteSignalBus. - Every
Subscribereturns anIDisposable— collect it and dispose it. Leaked subscriptions fire on recycled/destroyed objects.
1. Declare the signal
Section titled “1. Declare the signal”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 enablenamespace 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.
2. Publish
Section titled “2. Publish”private IPublisher<ArrowDamagedSignal> arrowDamagedPublisher = null!;private IPublisher<NoMovesAvailableSignal> noMovesPublisher = null!;
// payload signal — construct itthis.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.
3. Subscribe + dispose
Section titled “3. Subscribe + dispose”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:
| Owner | Subscribe in | Dispose in |
|---|---|---|
DI service (IInitializable) | Initialize() | Dispose() |
| Pooled entity / tile | OnSpawn() | OnRecycle() |
Plain MonoBehaviour | OnEnable() | OnDisable() / OnDestroy() |
4. Resolve the publisher/subscriber
Section titled “4. Resolve the publisher/subscriber”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>>();}5. Registration — nothing per-signal
Section titled “5. Registration — nothing per-signal”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.
6. SignalBus is obsolete
Section titled “6. SignalBus is obsolete”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:
| Obsolete | Replacement |
|---|---|
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.
Hard rules
Section titled “Hard rules”- Empty struct +
new—Publish(new XSignal())compiles and works, butPublish(default)is the house form. Consistency matters here because the empty-struct case is the one people copy. classsignal = per-publish heap allocation. In per-frame or per-collision publish paths that is GC pressure the profiler will find later.readonly structis not optional.- Mutable struct fields silently do nothing useful — subscribers receive a copy.
readonlyon 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 afterOnRecycleand touches a recycled object. - IL2CPP stripping —
MessagePipeandMessagePipe.VContainerare alreadypreserve="all"inAssets/Scripts/link.xml. If a new assembly holds only signal types and gets stripped, add it there. - Resolving in
OnSpawnre-resolves on every pool spawn. Resolve inOnInstantiate(once per instance), subscribe inOnSpawn. - No async/request handlers in this project.
IAsyncPublisher<T>andIRequestHandler<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.
Checklist for a new signal
Section titled “Checklist for a new signal”public readonly struct <Name>Signalin the feature’sSignals/folder, XML-documented.- No payload → body is
{ }; payload →readonlyfields + constructor. - Publisher: inject
IPublisher<T>, callPublish(default)(empty) orPublish(new T(...)). - Subscriber: inject
ISubscriber<T>,Subscribe(handler).AddTo(bag), dispose the bag on teardown. - Zero registration code — the root
RegisterMessagePipe()already covers it.