In this article, we will talk about reactive programming and how to implement them in Unity using Unity’s plugin UniRX
Reactive programming is a programming paradigm focuses on dealing with data flows and handling their effects on the codebase to change. This process is done asynchronously so it won’t affect the current code flow and it encapsulates the process of changing data so it can be useful from debugging to getting performance.
In imperative programming languages like C# we tell to program how to deal with the problem rather than what to do like in declarative programming. When we want to do something we need to check our conditions so we can learn if we can do it or not. This can be a simple if check or even a complex function that returns a state. When we want to update something we need to check it constantly and do something according to that state. And if something goes wrong program needs to know how it will proceed or it will be a failure.
Reactive programming aims to solve this problem by giving variables to the ability to inform us when something changes. Rather than we ask the program a status like is the game finished over and over again to do something in our code, we can tell it what to do when it changes and just leave it to work as it is.
Reactive programming made up to three key points: Observable, Observers and Schedulers
Observable: Observables are our data streams. They will continuously emit data so it can be observed and take actions according to them.
Observers: Observers are consumers of our data stream. They will subscribe to our observables to receive data. When they have received the data they will store it on their onNext() callback and after that, it can be used in various actions to filter and modify the data.
Schedulers: As we already mentioned reactive extensions works asynchronously so we can tell our observers to which thread they will observe with observeOn() method or which thread they will work on with scheduleOn()
For a quick example for UniRx, I prepared a simple example code piece here for an Enemy class which has a health property as an integer reactive property and we have a simple integer value of 10 for our damage variable. Of course, before we do any of these we need to install UniRx plugin from the Asset Store and reference it on top of our code.
We have a simple OnMouseDown() method for getting the click event on our enemy and when we do that our DoDamage() method gets called. In DoDamage() we make our health value decreased by the value of our damage and its simple as that. But wait, we didn’t do anything based on our changes on the health value. Here our UIManager class enters.
Our UIManager has a reference for the enemy and has subscribed to our enemy’s health property. This SubscribeToText() method automatically updates our healthText object in UI and we don’t need to add anything else to update it.