Data binding in Unity?

Is it possible to use the existing .NET data binding facilities to perform data binding within Unity?

I am hoping that I could bind properties and variables between different classes. If this is possible, I could perhaps also bind data between my gameobject properties and Unity GUI. I am aware that .NET has certain methods for doing data binding, such as BindingOperations.setBinding(). But these are mainly WPF and Windows Form libraries. It may not be available in Unity’s Mono.

If this is possible, how can I perform data binding with C# in Unity? Snippets and example codes will be very useful. Thanks.

You can use delegates and events. Check also this page.

Keep in mind that you will need caution and extra work to prevent memory leaks, especially when loading a new level. You must indeed release the connection between the sender and the subscriber explicitely. OnDestroy() could be of a great help.

I used this facility to make all GUI update themselves when the user switch language. I had a LanguageHelper with a LanguageChange event. All GUI with text register to this event. When it occurs, they ask the LanguageHelper for new text value (based on the current language).

That’s a really interesting question. I work with a different game engine that is explicitly based upon subscriber relationships, which are much like binding in C#. As soon as you set a variable the subscribers are notified etc.

I don’t see that pattern in Unity. It’s more of a “do something a million times a second over and over” type engine. You could design your own binding pattern if you want though. From what I’ve seen you may run into trouble with threading contexts since some threads are allowed to modify transform info while others are not.

I’ve found a way to implement data-binding in unity in my MVVM framework MarkUX. It was a bit tricky since unity likes to work with fields directly and not go through properties were you usually have your notify value changed logic. The way I did it requires the user to set values using a SetValue() method.

SetValue(() => PropertyName, value);

Through reflection it checks if the value is different and notifies any listeners. The bonus for solving it that way is that the user doesn’t have to bother with any NotifyPropertyChanged “plumbing” in his classes.

I’d be happy to share more implementation details if anyone is interested.