Skip to content

Instantly share code, notes, and snippets.

@HassakuTb
Last active August 10, 2019 22:22
Show Gist options
  • Save HassakuTb/ed66e6648a526efaf65e3f28946869c2 to your computer and use it in GitHub Desktop.
Save HassakuTb/ed66e6648a526efaf65e3f28946869c2 to your computer and use it in GitHub Desktop.
beat transmitter using UniRx
using System;
using UniRx;
using UnityEngine;
namespace KotonohaAnone.Presenter
{
public class BeatTransmitter : MonoBehaviour
{
[SerializeField] private AudioSource audioSource;
[SerializeField] private float bpm;
private readonly Subject<Unit> beatSubject = new Subject<Unit>();
// 曲の何ビート目か(前Update時)
private int previousBeatCount = 0;
private void Update()
{
float beatTime = 60f / bpm;
int currentBeatCount = Mathf.FloorToInt(audioSource.time / beatTime);
if(currentBeatCount != previousBeatCount)
{
beatSubject.OnNext(Unit.Default);
}
previousBeatCount = currentBeatCount;
}
private void OnDestroy()
{
beatSubject.Dispose();
}
// ビートを観測する
// 1拍ごとに発行される
public IObservable<Unit> ObserveBeat()
{
return beatSubject;
}
}
// 利用側
class Usage : MonoBehaviour
{
void SomeMethod()
{
BeatTransmitter beat = GetComponent<BeatTransmitter>();
beat.ObserveBeat()
.Subscribe(_=>
{
// ビートごとに何かする
})
.AddTo(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment