unity-atoms/docs/tutorials/unirx.md

80 lines
2.4 KiB
Markdown
Raw Normal View History

2019-10-03 19:37:30 -04:00
---
id: unirx
title: Usage with UniRX
hide_title: true
sidebar_label: Usage with UniRX
---
2019-10-03 17:05:26 -04:00
# Usage with UniRX
2019-10-07 19:06:38 -04:00
Variables and Events exposes methods that returns [`IObservables`](https://docs.microsoft.com/en-us/dotnet/api/system.iobservable-1?view=netframework-4.8). Atom Variables exposes `ObserveChange` and `ObserveChangeWithHistory`, while Atom Events exposes `Observe`. This makes it possible to use Unity Atoms seamlessly together with [UniRx](https://github.com/neuecc/UniRx).
## Simple example
The `HealthBar.cs` script from the [Basic tutorial](./basic-tutorial) could be rewritten like this using UniRx:
```cs
using UnityEngine;
using UnityEngine.UI;
using UniRx;
2019-10-08 18:13:33 -04:00
public class HealthBarUniRx : MonoBehaviour
2019-10-07 19:06:38 -04:00
{
[SerializeField]
private IntVariable _health = null;
void Awake()
{
_health.ObserveChange().Subscribe(health =>
{
2020-03-02 12:42:19 -05:00
GetComponent<Image>().fillAmount = 1.0f * health / _health.InitialValue;
2019-10-07 19:06:38 -04:00
});
}
}
```
## Advanced example
Here is another example of a `PlayerMove.cs` script that is a little bit more advanced. Horizontal and vertical input is only getting a value from the `Input` class as long as the UI state is in the state of `_uiStatePlaying`.
2019-10-08 17:51:21 -04:00
_NOTE: This example is also using [Marvelous](https://github.com/AdamRamberg/marvelous) for its `Fuse` method._
2019-10-07 19:06:38 -04:00
```cs
using System;
using UnityEngine;
using Marvelous;
using UniRx;
2020-03-02 13:36:52 -05:00
using UnityAtoms.BaseAtoms;
2019-10-07 19:06:38 -04:00
2019-10-08 18:13:33 -04:00
public class PlayerMoveUniRx : MonoBehaviour
2019-10-07 19:06:38 -04:00
{
[SerializeField]
private StringVariable _uiState;
[SerializeField]
private StringConstant _uiStatePlaying;
private void Awake()
{
float _horizontal = 0f, _vertical = 0f;
string HORIZONTAL = "Horizontal", VERTICAL = "Vertical";
2019-10-08 17:51:21 -04:00
Observable.EveryUpdate().Fuse<long, string>(
_uiState.ObserveChange(),
2019-10-07 19:06:38 -04:00
initialValue2: _uiState.Value
).Subscribe(t =>
{
2019-10-08 17:51:21 -04:00
var (_, state) = t;
_horizontal = state == _uiStatePlaying.Value ? Input.GetAxis(HORIZONTAL) : 0f;
_vertical = state == _uiStatePlaying.Value ? Input.GetAxis(VERTICAL) : 0f;
2019-10-07 19:06:38 -04:00
});
Observable.EveryFixedUpdate().Subscribe(t =>
{
GetComponent<Rigidbody2D>().velocity = new Vector2(_horizontal, _vertical) * 5f;
});
}
}
```
2019-10-08 17:51:21 -04:00
Using Unity Atoms together with UniRx and Marvelous (for its `Fuse`) makes your scripts really data driven.