Are you looking for a way to let things happen in Unity on a regular interval? Would you like to see an alternative to Co-routines and keeping track of delta-times in the Update-event? After reading this tutorial you are able to use Reactive Extensions to create an observable that emits a stream of updates every second and keeps track of the update count.

Interval timer in Unity using UniRx (Reactive Extensions).

interval cube

unity asset store

You should now find a UniRx folder in your project:

project

hierarchy

using System;
using UniRx;
using UnityEngine;

public class App : MonoBehaviour
{
public GameObject Cube;
private IDisposable _update;

void Start()
{
_update = Observable.Interval(TimeSpan.FromMilliseconds(1000)).Subscribe(x => // x starts from 0 and is incremented everytime the stream pushes another item.
{
    Cube.transform.rotation = UnityEngine.Random.rotation;
});
}

private void OnDestroy()
{
_update.Dispose();
}
}

In the code above, the result of Observable.Interval (an IDisposable) is stored in a member to properly dispose when the MonoBehavior is destroyed.

drag

Written by Loek van den Ouweland on 2018-01-12.
Questions regarding this artice? You can send them to the address below.