[RELEASED] Data Bind for Unity

Hi there!

The first version of Data Bind for Unity is available in the Asset Store! Check it out now for a very low initial price and help me with your feedback to further develop it for your needs!

Introduction:
A clean separation between logic/data and visualization is a must-have, not only in software projects (Separation of content and presentation - Wikipedia). This guarantees that the business logic of the application isn’t dependent on the presentation, so the visualization can be easily adapted.

One famous architecture, at least in the Microsoft universe, is the MVVM pattern (Model–view–viewmodel - Wikipedia) which is highly utilized in Windows Presentation Foundation (WPF, Windows Presentation Foundation - Wikipedia). I don’t want to get too much into detail of this framework as it a fully developed business framework with a huge amount of complex stuff.

The part we are interested in is the data binding between the view and the view model. The view model is an additional structure which sits between the view and the logic. It gets its data from the logic of the application and provides an interface for the view to use. Via data bindings the view can use the data provided by the view model to show it to the user.

This is what we adapted with our plugin, so you’ll have a common way how your UI is separated from you game logic to get many cool advantages:

  • Don’t be afraid that UI changes break your game any more, the logic is completely separated
  • Exchange your UI system without touching any logic (e.g. from NGUI to Unity UI)
  • Easily extend the plugin to use it with a custom UI, world objects or custom input commands

Example: Easy Health Bars

Tired of remembering to update two variables (actor.Health = 20.0f, healthLabel.Text = „20“) if the health of your character changed, so the UI is updated correctly?

No problem, Data Bind will take care of this from now on. You just update the data in your context and the UI will update magically!

Okay, not really magically, but without any work on your side. In principal it works like this:

  • The data variables in your context are wrapped in a so called “Data property”
  • The bindings on UI side register for value changes on this properties
  • When your code sets a new value for your data, the property informs its listeners, so they can update the UI properly.

In your code…

public class PlayerContext : Context
{
    #region Fields

    /// <summary>
    ///   Data binding property, used to get informed when a data change happened.
    /// </summary>
    private readonly Property<int> healthProperty = new Property<int>();

    #endregion

    #region Properties

    public int Health
    {
        get
        {
            return this.healthProperty.Value;
        }
        set
        {
            this.healthProperty.Value = value;
        }
    }

    #endregion
}

…at the same time on the UI side:

More information

Check out the official documentation with tutorials, examples, API and explanations. If any questions are left, just send me a message or post in this thread!

Hope our asset serves you as well as it does for our projects to keep your logic and presentation separated from each other! A big update with many additional bindings was already created and is reviewed currently. I’ll keep you updated when it arrives.

Version 1.0.1 is now available in the store! It contains many new bindings and some fixes/refactorings. Here is the detailed changelog:

  • CHANGED: Structure - Local path changed from DataBind to Slash.Unity.DataBind to fit namespaces
  • ADDED: Context - Getting value for context node possible from field as well.
  • FIXED: Property - Null reference check before converting value of data property.
  • CHANGED: Collection - Collection base class implements IEnumerable, not IEnumerable[object] so the type of the concrete collection is identified correctly in Linq queries.
  • CHANGED: Bindings - Only triggering setters in OnEnable if data binding was already initialized with initial data values.
  • FIXED: Command - Safe cast to delegate in Command.
  • CHANGED: Foundation - Changed BehaviourSingleGetter/Setter to ComponentSingleGetter/Setter.
  • CHANGED: Foundation - Created base class for ItemsSetter to use it for other collection setters as well.
  • CHANGED: UnityUI - Made GridItemsSetter for UnityUI more generic to work for all LayoutGroups.
  • CHANGED: Active Setter - Changed naming in menu from “Active” to “Active Setter”.
  • ADDED: Command - Reset method is used to set initial target behaviour.
  • ADDED: Bindings - Added several checks, formatters and setters: ComparisonCheck, EqualityCheck, ArithmeticOperation, InvertBoolFormatter, LogicalBoolFormatter, PrependSign, RoundToNearestOperation, TextFileContentFormatter, TimeFormatter, AnimatorBooleanSetter.
  • ADDED: NGUI - Added several setters/getters for PopupList, Button and Slider.
  • ADDED: Unity UI - Added serveral setters/getters for Slider and Image control.
  • ADDED: Foundation - ComponentSingleSetter checks if target is null before updating the component.
  • ADDED: Core - Throwing exception if invalid path is passed to context in RegisterListener, RemoveListener or SetValue.
  • CHANGED: Game Object Items Setter - Only created items are removed on clear, not all children.

Furthermore I wrote up a dev post on the weekend to explain how data binding in general and Data Bind for Unity in particular works:

http://unity-coding.slashgames.org/the-magic-behind-data-binding-part-1/

It’s the first part of a series of posts, covers how data properties and data contexts work internally and hopefully give you some insights. It isn’t required to understand the internals to use the asset though, but if you are as curious as I am it might be interesting to read anyway :slight_smile:

Ask all your questions about the asset right here in the thread, I’m eager to answer them!

1 Like

This is interesting, I may be looking at this wrong but is this primarily for UI?

Hi @cybervaldez ,

Happy to hear that it is interesting for you :slight_smile:

Many of the scripts are there to set the correct data values on UI controls, that’s right. But the data binding itself isn’t limited to UI, we already use it in our projects to place and setup the game objects in the game world.

For example the ActiveSetter just activates/deactivates a game object depending on a boolean data value, this doesn’t have to be a UI control. The GameObjectItemsSetter creates child game objects for a game object depending on a collection from the data context.

The thing is that the scripts for world objects are quite specific to the project, so that’s why there are not that many generic ones. I added some like the PositionSetter and the LocalPositionSetter. Something similar for rotation and scaling is very quickly done. See http://slashgames.org:8090/display/DBFU/Create+Your+Own+Setter for a short documentation how to add new setters.

If you can think of any further generic setters or need help writing your own ones, let me know :slight_smile:

Really interesting!
How is hard to use it with NGUI?

Hi @kenshin1 ,

Pretty easy, the steps are almost the same as with Unity UI. Many scripts are available for both UIs, Unity UI as well as NGUI. The examples are available for both, too.

All you have to do after importing the package is to extract the package NGUIExtensions in the Addons folder. This will import all NGUI specific scripts.

Great, thanks for the quick answer!

No problem :slight_smile: If you try the asset let me hear your feedback, I’m always looking for ways to improve it!

1 Like

Some more coding monkey gibberish on this boring Sunday? Here you go! It’s about commands in data binding and how the data of a data context is arranged (It’s a tree!).

http://unity-coding.slashgames.org/the-magic-behind-data-binding-part-2-commands-and-data-tree/

It should describe how our asset works behind the scenes. If you have any further questions, don’t hesitate to ask! :slight_smile:

This time Unity was a lot faster reviewing the update for Data Bind, so version 1.0.2 is already available in the Asset Store!

Besides some additional generic bindings which could be useful in many projects and some code refactoring, the biggest addition is a drop down to select the context data path from! This means you don’t have to type in the path manually anymore which should prevent type errors and let’s you also make sure you set up your hierarchy the way you wanted to:

1993605--128994--PathDropDown.png

It works for:

  • Setters
  • Getters
  • MasterPaths
  • Commands

To make the drop downs work correctly, the context type has to be specified in the ContextHolder script which is probably located at the root node of your UI.

Custom paths are still possible, e.g. if you want to access an ancestor data context with the “#” syntax.

Thanks to @sonicviz who wished for this feature after he had a look at our asset! :slight_smile:

Here’s the full changelog of version 1.0.2:

  • ADDED: Core - Added exceptions if trying to set a read-only property or method.
  • CHANGED: Core - DataNode sets value of field or property instead of data property, so even raw members of a context are updated correctly.
  • CHANGED: Bindings - Renamed GameObjectSetter to GameObjectSingleSetter.
  • CHANGED: Core - Made some methods of context holder virtual to allow deriving from the class if necessary.
  • FIXED: Data Bind - Returning path to context if no path is set after #X notation.
  • CHANGED: Data Bind - Logging error instead of exception if invalid path was specified (on iOS exceptions caused a crash).
  • CHANGED: Editor - Adjusted component menu titles for bindings to be more consistent.
  • ADDED: Setters - Added binding to create a child game object from a prefab with a specific context.
  • ADDED: GraphicColorSetter - Setter for color of a Graphic component (e.g. Text and Image).
  • CHANGED: ArithmeticOperation - Checking second argument for zero before doing division to avoid exception.
  • ADDED: Unity UI - Added SelectableInteractableSetter to change if a selectable is interactable depending on a boolean data value.
  • ADDED: Operations - Added sprite loader which loads a sprite depending on a string value.
  • ADDED: Core - Added log error when context is not derived from Context class, but path is set. This may indicate that the user forgot to derive from Context class.
  • ADDED: Context Path - Added property drawer for a context path property.
  • CHANGED: Context Holder - Only creating context automatically if explicitly stated and no context is already set in Awake.

My co-founder Nick wrote a new tutorial where he describes how you can extend the asset with your own scripts, e.g. one that converts a string to upper characters before assigning it to a text/label:

http://slashgames.org:8090/display/DBFU/Create+Your+Own+Formatter

It’s a really clean and reusable way of extending the functionality. If you have ideas for cool scripts that we should add to the asset, let us know!

Enjoy the read!

The Link does not work on my end

Hi @zyzyx ,

Which one doesn’t work, http://slashgames.org:8090/display/DBFU/Create+Your+Own+Formatter ? Just tested it on my side, it works here. Or do you mean another link?

Yes the Formatter link and the link to the documentation. Mybe it gets blocked somewhere on my end.

That’s strange, never heard of a problem with the address. Does http://www.slashgames.org/ work?

I’m in the office so it probably gets blocked by the firewall. If I use a proxy it works :slight_smile:

Phew, so it’s not on our side, good :slight_smile: Thanks for checking out! Hope you like the asset and find it useful.

Thanks! I intend using your asset in two of our upcoming mobile apps :slight_smile:

Nice :slight_smile: Let me know if you run into any problems. We used the asset for our own projects already but there might be some issues which weren’t discovered yet.

Next version 1.0.3 is out! Main change in this one is the correct Windows 8 Phone and Store support. It was already in there, but not properly tested. Now it should work without problems :slight_smile:

Here’s the full changelog: