What is this fascinating Rebind Operation design pattern?

Hey all! I have to admit that lately, you fine Unity folks have kept me busy learning new design patterns as I’m implementing some of your new packages. This Rebind Operation pattern is totally new to me, and it’s fascinating. I was hoping someone was in the mood to enlighten me by explaining how it works:

m_RebindOperation?.Dispose();
m_RebindOperation = m_Action.PerformInteractiveRebinding()
    .WithControlsExcluding("<Mouse>/position")
    .WithControlsExcluding("<Mouse>/delta")
    .OnMatchWaitForAnother(0.1f)
    .OnComplete(operation => ButtonRebindCompleted());
  • If the object isn’t null already, we “Dispose” it. Why? Don’t we have a garbage collector? Is this related to some kind of low level C++ stuff?
  • How exactly does this stack of methods resolve its self? I assume that each one… creates (?) a new RebindOperation object that somehow merges in the value of the previous one? That’s quite clever. Where is this pattern common? I have never seen it before.
  • What triggers the rebind operation? is that somehow implemented inside of the “OnComplete” assignment? If so, does the OnComplete assignment have to be at the end of the chain here? I would expect some kind of “okay, now do it” method call to follow all this.

The pattern is usually called “fluent” in some way or other. You can read more about it here.

Unfortunately yes, it is. One thing that RebindingOperation holds on to is an InputControlList which in turn holds on to unmanaged C++ memory and thus needs to be disposed of.

The chain shares a single RebindingOperation so no actual allocations happen as part of the method chain. Different APIs in the input system do the same in different ways. Some just pass structs around that encapsulate the relevant context.

The pattern has become somewhat common in configuration-style APIs. For example, mocking frameworks (like JustMock and Moq, for example) tend to employ the pattern extensively.

The Start() method is the “okay, now do it”. It’ll hook itself into input event processing and thus have the rebind operation run in the background.

1 Like

Wow, fascinating. Thank you very much for the detailed response! I can feel myself getting smarter.

So even though this object doesn’t derive from monobehaviour, you Unity ninjas are hooking it into the event processing system anyway. veeeery sneaky.

Everything’s working nicely so far, once I’ve managed to get my head around this new system. Thanks again!